kah*_*oha 6 javascript cookies reactjs next.js react-cookie
考虑下面的代码
Index.getInitialProps = async function({req}) {
const res = await fetch("http://localhost/api/tiles");
const json = await res.json();
}
Run Code Online (Sandbox Code Playgroud)
假设/api/tiles端点需要访问uid用户的 cookie。正常情况下,一个人就可以了{credentials: "include"}。但如何在 Next.js 中执行此操作?
如果您使用的是 v13.4.0 以上版本,有两种方法可以包含用于前端获取和后端获取的 cookie。
const res = await fetch('/url', {credentials: 'include'})
Run Code Online (Sandbox Code Playgroud)
import {cookies} from 'next/headers';
const getCookie = async (name: string) => {
return cookies().get(name)?.value ?? '';
}
const cookie = await getCookie('cookie-name');
const res = await fetch('/url', {
headers: {
Cookie: `cookie-name=${cookie};`
}
});
Run Code Online (Sandbox Code Playgroud)
Tes*_*ter -2
当您使用时React(NextJS 是基于 ReactJS 构建的),您可以使用react-cookie来获取存储在系统中的 cookie。
安装react-cookie
npm install react-cookie
Run Code Online (Sandbox Code Playgroud)
如果您使用 Reactjs 版本,>= 16.8.0则可以使用 React hooks。
const [cookies, setCookie, removeCookie] = useCookies(['cookie-name']);
Run Code Online (Sandbox Code Playgroud)
您可以使用 设置 cookiesetCookie(name, value, [options])并获取 cookiecookie.get(name, [options])
所以在你的情况下代码应该看起来像
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10971 次 |
| 最近记录: |