首页 > 解决方案 > nextjs cookie 未添加到 axios 请求客户端

问题描述

我有一个在 UI 端使用 nextjs 并在 API 上使用 nestjs 的应用程序。

在 nestjs 中,我使用基于护照 cookie 的身份验证。

我正在使用 authCookieHeader 设置请求标头:

export const authCookieHeader = (session) => {
 const { accessToken, refreshToken } = session;
 const cookieVal = `${accessToken}; ${refreshToken};`;
 return {
    headers: {
        Cookie: cookieVal,
        withCredentials: true,
    },
 };
};

在服务器端 props 中进行调用时,cookie 被添加到来自 nextjs 的 axios 请求中。

 const config = authCookieHeader(session);
 let profile = {};
 if (session) {
    try {
        const resp = await axios.get(
            process.env.SH_API_BASEURL + `/users/profile`,
            config
        );
    ....
 }

但在客户端,cookie 未添加到 axios 请求中,我收到“未登录”错误

const config = authCookieHeader(session);
        console.log('config in client');
        console.log(config);
        const url = process.env.NEXT_PUBLIC_SH_API_BASEURL + '/users/profile';
        console.log(url);
        const { data: test1 } = await axios.get(url, config);
        console.log(test1);

在客户端中,axios 配置是

headers:  { Cookie: "Authentication=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEzNTQ1N2FiLWI4MGUtNDU2OC1hY2RiLWNiODZmYTJlNGQxMyIsImlhdCI6MTYyOTAxNTIxNiwiZXhwIjoxNjI5OTE1MjE2f" }

标签: cookiesaxiosnext.js

解决方案


推荐阅读