如何使用middleware.ts更新Next 13中的请求体?

bpzcxfmw  于 2023-06-29  发布在  其他
关注(0)|答案(2)|浏览(88)

我想使用中间件函数重写NEXT 13中的请求体:

import { NextRequest, NextResponse } from 'next/server';

enum MiddlewareRoutes {
    ACCESS = '/api/access',
}

const middlewareHandler = async (
    route: MiddlewareRoutes,
    response: NextResponse
): Promise<NextResponse> => {
    switch (route) {
        case MiddlewareRoutes.ACCESS: {
            response.cookies.set({
                name: 'vercel',
                value: 'fast',
                path: '/',
            });
            return response;
        }
        default: {
            return response;
        }
    }
};

export async function middleware(request: NextRequest) {
    const response = NextResponse.next();
    request.headers.set('ABC', 'DEG');
    request.body = { hello: 'world' };
    const newResponse = await middlewareHandler(
        (request?.nextUrl?.pathname ?? '') as MiddlewareRoutes,
        response
    );
    return newResponse;
}

export const config = {
    matcher: ['/api/:path*'],
};

但我得到错误说请求是只读属性。如何在NEXT 13中操作请求体?

42fyovps

42fyovps1#

您不能更新请求正文。只能更新标题。from this github post

// pages/api/hello.ts
export default (req, res) => {
  const valueFromMiddleware = req.headers['x-hello-from-middleware']
  return res.send(valueFromMiddleware)
}

// middleware.ts
import { NextRequest, NextResponse } from 'next/server'

export default function middleware(request: NextRequest) {
  // Clone request headers
  const headers = new Headers(request.headers);
  // Add a new request header
  headers.set('x-hello-from-middleware', 'foo');
  // Delete a request header from the client
  headers.delete('x-from-client');

  const resp = NextResponse.next({
    // New option `request.headers` which accepts a Headers object
    // overrides request headers with the specified new ones.
    request: {
      headers
    }
  });

  // You can still set *response* headers to the client, as before.
  resp.headers.set('x-hello-client', 'bar');
  return resp;
}
xbp102n0

xbp102n02#

如果您想修改请求头,这里有一个替代方法

export default function middleware(request: NextRequest) {
  const headers = new Headers(request.headers);
  headers.set('ABC', 'DEG');

  //...

}

您还可以访问请求体,如

const requestBody = await request.json()

进一步阅读
https://developer.mozilla.org/en-US/docs/Web/API/Headers
https://developer.mozilla.org/en-US/docs/Web/API/Request

相关问题