Next.js server side component request, how to send my cookie token?

题意:Next.js 服务器端组件请求时,如何发送我的 Cookie 令牌?

问题背景:

My Next.js is 14.1.0 and I'm using App router.

我的 Next.js 版本是 14.1.0,并且我正在使用 App 路由

async function Page() {
  const dataPromise: Promise<any> = getData();
  const data = await dataPromise;
  console.log('data: ', data);
  return (
    ....
  );
}

getData is a simple function which I make a request to the Django rest API. If there is a token in the cookie, requests can be made to protected services.

getData 是一个简单的函数,我用它向 Django REST API 发起请求。如果 cookie 中有令牌,就可以对受保护的服务进行请求。

When I make the same request on the client side, the response is 200 (OK) because I have a token. However, when I make a request on the server side, I get a 401 (Unauthorized) error.

当我在客户端发起相同的请求时,响应是 200(OK),因为我有令牌。然而,当我在服务器端发起请求时,我收到 401(未经授权)错误。

I guess the server side does not see my token when I make a request. How can I solve this problem? How do I use my token for server side fetching?

我猜服务器端在我发起请求时没有看到我的令牌。我该如何解决这个问题?如何在服务器端获取时使用我的令牌?

问题解决:

When you make a request from the browser to get the page, your cookies are sent along. You can grab your token using the cookies() function of Next.js and pass it to getData inside which you set the Authorization header:

当你从浏览器发起请求以获取页面时,cookie 会随之发送。你可以使用 Next.js 的 `cookies()` 函数获取你的令牌,并将其传递给 `getData`,在其中设置 `Authorization` 头部:

import { cookies } from "next/headers";

export default async function Page() {
  const cookieStore = cookies();
  const accessToken = cookieStore.get("access_token");
  const data = await getData(accessToken);
  return "....";
}

The Cookies.get('access_token') you said you are using in the comments is I guess working with browser APIs and not looking inside HTTP headers.

你在评论中提到的 `Cookies.get('access_token')` 我猜是与浏览器 API 一起使用的,而不是查看 HTTP 头部中的内容。

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143484890