如何修改Next.js中间件文件中的请求对象?

Yul*_*ale 5 middleware request httprequest request-object next.js

如何修改 Next.js中间件文件中的请求对象?

我看过这个问题,但它没有回答我的问题。

我有一个如下所示的中间件文件:

// middleware.js    
export function middleware(request: NextRequest) {
    req.name = "foo";
    //If I console.log req.name I see it is equal to foo.
    console.log(req.name) // logs "foo"
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个像下面这样的 api 路由

// pages/api/hello.js
export default async function handler(req, res) {
    console.log( req.name ) //logs undefined
    // what can I do so that I can access the new properties
    // I put in the req object in the middlware file here?
}
Run Code Online (Sandbox Code Playgroud)

小智 0

从 NextJs v 13.0.0 开始,有一个解决方法设置标头 https://nextjs.org/docs/advanced-features/middleware

//middleware.js
import { NextResponse } from 'next/server'

export async function middleware (req, res) {
  // NextJs doesn't allow you to modify the request object. So the only way to pass the data to the client is to add it to the headers of a new request.
  const requestHeaders = new Headers(req.headers)
  requestHeaders.set('xname', "foo")

  // And the middleware expects a response object as a return so we need to involve that as well.
  const response = NextResponse.next({
    request: {
      // New request headers
      headers: requestHeaders
    }
  })

  return response
}
Run Code Online (Sandbox Code Playgroud)

在api中您可以访问标头

// pages/api/hello.js
export default async function handler(req, res) {
    const nameHeader = req.headers.xname
    console.log('Hello '. nameHeader) // Hello foo
}
Run Code Online (Sandbox Code Playgroud)

如果您想以这种方式传递更多数据,您还可以将标头设置为 JSON 对象,但我建议稍微限制一下,以保持标头的大小较小并避免 431 错误“请求标头字段太大”