英文:
App-Router: How to persist API-Header for next request
问题
我目前遇到以下问题:
从API GET请求中,我获得一个etag
标头,我需要将其保留在缓存中,以便在可能发送的UPDATE或DELETE请求中作为If-Match
标头。
我尝试将其保存在服务器端Cookie中,代码如下:
// app/api/cart/[cartId]/route.ts
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
import { createGlueServerClient } from '@/src/lib/http/client/client.glue.server';
import { cookies } from 'next/headers';
function setEtagFromResponse(response: Response) {
const etag = response.headers.get('etag');
if (etag) {
cookies().set('etag', etag);
}
}
const GET = withApiAuthRequired(async (request: Request, { params }: { params: { cartId: string } }) => {
const client = createGlueServerClient();
const response = await client.get(`carts/${params.cartId}`, {
withAuth: true,
});
setEtagFromResponse(response);
return NextResponse.json(await response.json());
});
export { GET };
但是,当我尝试在PATCH请求中使用cookies().get('etag').value
获取它时,它就不在那里...
英文:
I currently struggle with the following issue:
From an API-GET-Request I get an etag
-Header I need to persist in the cache for a possible UPDATE?DELETE Request to be sent as If-Match
-Header.
I try to save it in a Server-Side-Cookie like this:
// app/api/cart/[cartId]/route.ts
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
import { createGlueServerClient } from '@/src/lib/http/client/client.glue.server';
import { cookies } from 'next/headers';
function setEtagFromResponse(response: Response) {
const etag = response.headers.get('etag');
if (etag) {
cookies().set('etag', etag);
}
}
const GET = withApiAuthRequired(async (request: Request, { params }: { params: { cartId: string } }) => {
const client = createGlueServerClient();
const response = await client.get(`carts/${params.cartId}`, {
withAuth: true,
});
setEtagFromResponse(response);
return NextResponse.json(await response.json());
});
export { GET };
But when I try to get it with cookies().get('etag').value
in the PATCH-Request, it's just not there...
答案1
得分: 1
一个更好的方法是在GET响应头中返回etag
的值。这样,客户端可以从响应中读取它,然后在随后的PATCH / DELETE请求中使用它。使用Cookie的方法会容易受到竞争条件的影响。
英文:
A better approach would be to return the etag
value in the GET response header. This way a client can read it from the response, and then use it in a subsequent PATCH / DELETE request. The cookies approach would be prone to race condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论