简体   繁体   English

如何在 Nextjs 中包含 cookies 和获取请求

[英]How to include cookies with fetch request in Nextjs

Consider the following code考虑以下代码

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

Suppose the /api/tiles endpoint needs access to the uid cookie on the user.假设/api/tiles端点需要访问用户的uid cookie。 Normally, one would do {credentials: "include"} .通常,一个人会做{credentials: "include"} But how do I do this in Next.js?但是我如何在 Next.js 中执行此操作?

As you are using React (NextJS is built on ReactJS) you can use react-cookie to get and cookies that are stored in the system.当你使用React (NextJS 建立在 ReactJS 之上)时,你可以使用react-cookie来获取存储在系统中的 cookies。

Install react-cookie安装react-cookie

npm install react-cookie

If you are using Reactjs with version >= 16.8.0 you can use React hooks.如果您使用版本>= 16.8.0的 Reactjs,则可以使用 React hooks。

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

You can set cookie with setCookie(name, value, [options]) and get the cookies with cookie.get(name, [options])您可以使用setCookie(name, value, [options])设置 cookie 并使用 cookie.get(name, [options]) 获取cookie.get(name, [options])

So in your case the code should look like所以在你的情况下,代码应该看起来像

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM