最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Next.js call self api , origin is always nothing - Stack Overflow

programmeradmin4浏览0评论

Here is my middleware

import { NextResponse, NextRequest } from 'next/server';
import { headers } from 'next/headers'
 
import { verifyJWT } from '@/lib/jwt';

// In-memory store for rate limiting
const rateLimitStore = new Map();

const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const MAX_REQUESTS = 500; // Max requests allowed in the window

export async function middleware(request: NextRequest) {
console.log(headers);
  const origin = request.headers.get('origin') || '';
  const host = request.headers.get('host') || '';
  console.log('Origin:', origin);
  console.log('Host:', host);

  const allowedOrigins = ['http://localhost', ''];
  const allowedHosts = ['localhost', 'example']; // Adjust based on your local/production domain
  const pathname = request.nextUrl.pathname;
  console.log('Pathname:', pathname);

  // Allow /api/socket without strict origin check (e.g., for WebSocket or specific clients)
  if (pathname.startsWith('/api/socket')) {
    const modifiedRequest = request.clone();
    const country = request.headers.get('cf-ipcountry') || 'HK';
    modifiedRequest.headers.set('x-user-country', country);
    const response = NextResponse.next(modifiedRequest);

    if (allowedOrigins.includes(origin)) {
      response.headers.set('Access-Control-Allow-Origin', origin);
      response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    }
    if (request.method === 'OPTIONS') {
      response.headers.set('Access-Control-Max-Age', '86400');
    }
    return response;
  }

  // Block null Origin unless Host matches allowed domain (same-origin check)
  if (!origin && !allowedHosts.some(allowedHost => host.includes(allowedHost))) {
    console.log('Blocking request - Null origin from unauthorized host:', host);
    return NextResponse.json(
      { error: 'Access denied: Missing origin from unauthorized host' },
      { status: 403 }
    );
  }

  // Block unallowed cross-origin requests
  if (origin && !allowedOrigins.includes(origin)) {
    console.log('Blocking request - Unauthorized origin:', origin);
    return NextResponse.json(
      { error: 'Access denied: Invalid origin' },
      { status: 403 }
    );
  }

  // Clone request and add custom header
  const country = request.headers.get('cf-ipcountry') || 'HK';
  const modifiedRequest = request.clone();
  modifiedRequest.headers.set('x-user-country', country);

  // Create response for allowed requests
  const response = NextResponse.next(modifiedRequest);

  // Set CORS headers for allowed origins (not null origin, unless cross-origin explicitly allowed)
  if (allowedOrigins.includes(origin)) {
    response.headers.set('Access-Control-Allow-Origin', origin);
    response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  }

  // Handle CORS preflight (OPTIONS) requests
  if (request.method === 'OPTIONS') {
    response.headers.set('Access-Control-Max-Age', '86400');
    return response;
  }


  return response;
}

export const config = {
  matcher: '/api/:path*', // Apply to all API routes
};

when i run the app in localhost, calling http://localhost/api/hello/get ,the origin is '', and the host is http://localhost

when i put the app in remote server ()

calling ,the origin is '', and the host is

As a result, every where can make use my api because the origin is always '', and the host is always

do anyone know how to config cors policy in next.js?

发布评论

评论列表(0)

  1. 暂无评论