【发布时间】:2021-05-07 12:22:59
【问题描述】:
我将 NextJS 与服务器端渲染一起使用
我使用带有 access_token (JWT) 的身份验证服务
我无法将 access_token 存储在 localStorage 中,因为它在 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;
【问题讨论】:
标签: node.js reactjs axios jwt next.js