乐闻世界logo
搜索文章和话题

How to include cookies with fetch request in Nextjs

1 年前提问
10 个月前修改
浏览次数193

1个答案

1

在 Next.js 中,如果需要在服务端发起请求并且想要携带来自用户的 cookie,首先需要了解的是,请求可以在两个不同的环境中发起:浏览器端(客户端)和服务器端。

客户端请求

当在客户端(即浏览器环境)中发起请求时(例如,在 useEffect 钩子中或者事件处理函数中),cookie 通常会自动随着请求发送,只要请求的是同源地址或者已经正确设置了 CORS 策略来允许 credentials。例如,你可以使用 fetch API:

javascript
fetch('https://your-api-domain.com/path', { method: 'GET', // 或者 'POST', 'PUT', 等 credentials: 'include', // 确保携带 cookie }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));

属性 credentials: 'include' 确保了即使是跨域请求,cookie 也会被携带。如果你的请求是同源的,那么使用 credentials: 'same-origin' 就足够了。

服务器端请求

在 Next.js 的服务器端(例如在 getServerSidePropsgetInitialProps 中),请求不会自动携带 cookie,因为这些代码运行在服务器上,不会自动获得浏览器中的 cookie。因此,你需要手动将 cookie 从请求头中提取出来,并附加到服务端的请求头中。

下面是一个 getServerSideProps 中如何带上 cookie 的例子:

javascript
export async function getServerSideProps(context) { const { req } = context; const cookies = req.headers.cookie; const res = await fetch('https://your-api-domain.com/path', { method: 'GET', headers: { // 需要手动设置 cookie cookie: cookies || '' }, credentials: 'include' // 对于跨域请求,这里同样需要设置 }); const data = await res.json(); // 返回 props return { props: { data }, // 将数据作为 props 传递给页面 }; }

在这个例子中,我们首先从请求上下文(context.req)中获取到从浏览器传来的 cookie,然后在服务端请求 API 时,将这些 cookie 设置在请求头中。

请注意,处理 cookie 时要确保考虑到安全性问题,不要在不安全的环境下暴露敏感信息,并且确保遵循相关的 HTTP 规范和最佳实践。

2024年6月29日 12:07 回复

你的答案