sin*_*090 5 node.js jwt reactjs axios next.js
我将 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;
Run Code Online (Sandbox Code Playgroud)
你可能想使用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: '/' })
...
}
Run Code Online (Sandbox Code Playgroud)
来自 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: '/' })
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3286 次 |
| 最近记录: |