如何在Next中修改请求对象,js中间件文件?

liwlm1x9  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(122)

如何在Next中修改request对象。js middleware file
我看过this question,但它没有回答我的问题。
我有一个中间件文件,如下所示:

// 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"
}

然后我有一个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?
}
qeeaahzv

qeeaahzv1#

下一篇:NextJs v 130.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
}

在API中你可以访问header

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

如果你想通过这种方式传递更多的数据,你也可以将头部设置为JSON对象,但我建议有点限制,以保持头部的大小,并避免431错误“请求头部字段太大”

相关问题