gpt4 book ai didi

node.js - 如何在 NextJS SSR 中存储和获取 access_token

转载 作者:行者123 更新时间:2023-12-04 13:29:20 26 4
gpt4 key购买 nike

我将 NextJS 与服务器端渲染一起使用
我使用带有 access_token (JWT) 的身份验证服务
我无法在 localStorage 中存储 access_token因为它在 getServerSideProps 中不可用
所以我把 access_token 放在了 httpOnly cookie在服务器上可用。
我在服务器上有一些请求,在客户端上有一些请求,所以我需要通过两种方式获取 access_token,在服务器上来自 req.headers.cookie和来自 document.cookie 的客户端
我想写 axios 拦截器来将 access_token 添加到每个请求中。
这适用于客户端,但我能为服务器端做什么?

import axios from 'axios';

const _axios = axios.create();
axiosInstance.interceptors.request.use(function (config) {
let token;

// check if it's on the client-side
if(typeof document !== 'undefined')
token = getToken(document.cookie);

// how to check for server-side and how to get cookie ?

return {
...config,
headers: {
'Authorization': `Bearer ${token}`
}
};
}, function (error) {
return Promise.reject(error);
});

export default axiosInstance;

最佳答案

您可能想使用 nookies
从 getServerSideProps

export async function getServerSideProps(ctx) {

//Parse cookies from request header
const cookies = nookies.get(ctx)

//Set cookies on response header
nookies.set(ctx, 'key', 'token', { path: '/' })

...

}
从 API 路由
export default function handler(req, res) {

//Parse cookies from request header
const cookies = nookies.get({ req })

//Set cookies on response header
nookies.set({ res }, 'key', 'token', { path: '/' })

...
}

关于node.js - 如何在 NextJS SSR 中存储和获取 access_token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66024661/

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