如何在 Nextjs 中包含带有获取请求的 cookie

How to include cookies with fetch request in Nextjs

考虑以下代码

Index.getInitialProps = async function({req}) {
  const res = await fetch("http://localhost/api/tiles");
  const json = await res.json();
}

假设 /api/tiles 端点需要访问用户的 uid cookie。 通常,一个人会做 {credentials: "include"}。 但是我如何在 Next.js 中执行此操作?

当您使用 React(NextJS 建立在 ReactJS 之上)时,您可以使用 react-cookie 来获取和存储在系统中的 cookie。

安装react-cookie

npm install react-cookie

如果您使用 >= 16.8.0 版本的 Reactjs,您可以使用 React hooks。

const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);

您可以使用 setCookie(name, value, [options]) 设置 cookie 并使用 cookie.get(name, [options])

获取 cookie

因此在您的情况下,代码应如下所示

import { useCookies } from 'react-cookie';
const [cookies, setCookie] = useCookies(['name']);

Index.getInitialProps = async functon({req}) {
  cookie = cookies.get(name)
  const res = await fetch("http://localhost/api/tiles", cookie);
  const json = await res.json();
}