我想使用中间件函数重写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中操作请求体?
2条答案
按热度按时间42fyovps1#
您不能更新请求正文。只能更新标题。from this github post
xbp102n02#
如果您想修改请求头,这里有一个替代方法
您还可以访问请求体,如
进一步阅读
https://developer.mozilla.org/en-US/docs/Web/API/Headers
https://developer.mozilla.org/en-US/docs/Web/API/Request