You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js URL重写与中间件未携带请求头问题求助

问题

需要将http://localhost:3000/backend路径的API请求转发到部署在http://localhost:5186/api的.NET Core项目,请求需携带JWT令牌。但.NET Core端无法获取到请求头,怀疑是跨域或请求头传递配置问题,询问如何配置Next.js让请求正确携带头信息。

现有配置代码

next.config.js

module.exports = {
  async rewrites() {
    return [
      {
        source: "/backend/:path*",
        destination: `${API_URL}/:path*`,
      },
    ];
  },
};

Middleware.ts

import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@auth0/nextjs-auth0/edge';

export async function middleware(req: NextRequest) {
 
  const res = NextResponse.next();
  const user = await getSession(req, res);

  if (user) {
    req.headers.append('Authorization', `Bearer ${user.accessToken}`)
  }

  console.log(res.headers);
  return res;
};

解决方案

你的问题核心在于:middleware中修改的是客户端发送给Next.js的请求头,但Next.js的rewrites配置是服务器端发起的独立请求到.NET API,两者请求头上下文不共享,所以修改后的头不会自动传递过去。需要在middleware中手动处理请求转发并携带Authorization头,具体修改如下:

1. 修改Middleware.ts

import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@auth0/nextjs-auth0/edge';

export async function middleware(req: NextRequest) {
  // 仅匹配/backend开头的请求
  if (req.nextUrl.pathname.startsWith('/backend')) {
    const res = NextResponse.next();
    const user = await getSession(req, res);
    
    // 构造目标API的URL:替换/backend为/api,指向.NET Core服务地址
    const targetUrl = new URL(
      req.nextUrl.pathname.replace('/backend', '/api'),
      'http://localhost:5186'
    );
    // 保留原请求的查询参数
    targetUrl.search = req.nextUrl.search;

    // 复制原请求头,添加Authorization令牌(如果存在)
    const headers = new Headers(req.headers);
    if (user?.accessToken) {
      headers.set('Authorization', `Bearer ${user.accessToken}`);
    }

    // 转发请求到.NET Core API
    const apiResponse = await fetch(targetUrl.toString(), {
      method: req.method,
      headers: headers,
      body: req.method !== 'GET' && req.method !== 'HEAD' ? await req.text() : undefined,
      credentials: 'include' // 如需传递Cookie可保留,否则移除
    });

    // 将API的响应返回给客户端
    return new NextResponse(apiResponse.body, {
      status: apiResponse.status,
      statusText: apiResponse.statusText,
      headers: apiResponse.headers
    });
  }

  // 其他路径请求按原有逻辑处理
  return NextResponse.next();
};

// 指定middleware仅作用于/backend路径
export const config = {
  matcher: ['/backend/:path*']
};

2. 移除next.config.js中的rewrites配置

既然已经在middleware中处理了请求转发,next.config.js里的rewrites规则可以删除,避免冲突。

3. 确保.NET Core端CORS配置正确

在.NET Core的Program.cs中添加CORS策略,允许http://localhost:3000的请求携带Authorization头:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowLocalhost3000", policy =>
    {
        policy.WithOrigins("http://localhost:3000")
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

// 在UseRouting之后、UseAuthorization之前启用CORS
app.UseCors("AllowLocalhost3000");

说明

原来的middleware修改req.headers仅对Next.js内部路由生效,而rewrites是服务器端发起的独立请求,两者的请求头上下文不共享。通过在middleware中手动转发请求并构造包含Authorization头的请求,才能确保令牌被传递到.NET Core端。

内容的提问来源于stack exchange,提问作者NullReference

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:07:21