gpt4 book ai didi

Server side rendering doesn't work with Axios withCredentials(服务器端渲染不适用于带有Credentials的Axios)

转载 作者:bug小助手 更新时间:2023-10-28 21:57:24 25 4
gpt4 key购买 nike



I've an application with Laravel as backend and NextJs 13 (app router) as frontend. I'm using Sanctum in laravel for login and when the user is logged laravel send 2 cookies, one is httpOnly and another is a client cookie as we can see in the image

我有一个应用程序,后台是Laravel,前端是NextJs13(应用程序路由器)。我正在使用Sancum in laravel进行登录,当用户登录时,laravel发送两个Cookie,一个是HttpOnly,另一个是客户端Cookie,如我们在图像中所见


enter image description here


In NextJs is working as expected when I call the endpoints to Laravel because I'm using Axios and I set withCredentials where the cookies is sent automatically in each request.

在NextJs中,当我将端点调用到Laravel时,它按预期工作,因为我使用Axios,并且我设置了withCredentials,在每个请求中自动发送cookie。


Axios:

Axios:


function createHttpClient(baseURL) {
return axios.create({
baseURL,
withCredentials: true,
headers: {
'Content-type': 'application/json'
}
})
}

and the request has both cookies:

并且该请求有两个Cookie:


enter image description here


The problem I have is in NextJs with server side rendering, I have a page where in this case I need to get the data as static site generation

我遇到的问题是在服务器端呈现的NextJs中,我有一个页面,在这种情况下,我需要在静态站点生成时获取数据


export default async function Page() {
const response = await CategoryService.getAll();
const categories = response.data.data;

return (
<CategoryView categories={categories} />
)
}

the problem here is that the cookies are not sent, so the response is Unauthorize

这里的问题是没有发送Cookie,因此响应是未经授权的


response: {
status: 401,
statusText: 'Unauthorized',
headers: AxiosHeaders {
server: 'nginx/1.21.6',
'content-type': 'application/json',
'transfer-encoding': 'chunked',
connection: 'close',
'x-powered-by': 'PHP/8.1.2',
'cache-control': 'no-cache, private',
date: 'Sat, 09 Sep 2023 13:21:49 GMT',
'access-control-allow-origin': 'http://localhost:3000',
'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
'access-control-allow-headers': 'Origin, Content-Type, Accept, Authorization, X-Request-With, lang',
'access-control-allow-credentials': 'true',
'set-cookie': [Array]
},

I don't know how to add the cookies in server side rendering in next

我不知道如何在Next的服务器端渲染中添加Cookie


更多回答
优秀答案推荐

That's the normal behaviour. Your cookies is set in browser. Remember, Next.js SSR is happening on server. Server doesn't have access to your browser cookies automatically. What you need to do is manually pass the cookie to your axios from header

这是正常的行为。您的Cookie已在浏览器中设置。请记住,Next.js SSR正在服务器上进行。服务器无法自动访问您的浏览器Cookie。您需要做的是手动将cookie从Header传递给您的axios


import { cookies } from 'next/headers';

Then in your function you can get do cookies().get(KEY_NAME) & add to axios

然后在您的函数中可以获取do cookies().get(Key_Name)&添加到axios


更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com