如何在下一次请求中保持API标头的持久性。

huangapple go评论55阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月26日 20:01:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定