【发布时间】:2022-01-13 02:41:49
【问题描述】:
我在 next-js 应用程序中,我的身份验证令牌存储在 cookie 中。 对于某些原因,我使用 Swr 和 Api 路由来获取我的安全 api 后端。 我正在尝试找到一种方法将我的身份验证令牌放入所有 api 请求中。
在设置登录 cookie 期间
res.setHeader(
'Set-Cookie',
cookie.serialize('token', data.access_token, {
httpOnly: true,
secure: process.env.NODE_ENV !== 'development',
maxAge: data.expires_in, // 1 week
sameSite: 'strict',
path: '/',
}),
);
这是一个使用 swr fetch 的页面示例
//page/test.ts - example of my test route
const { data, error } = useFetchContent(id);
if (error) {
showError('error');
replace('/');
}
return <DisplayContent content={data} />
这是一个 swrFetchHook
// fetchContentHook
function useFetchContent(id: string): ContentDetail {
return useSWR<any>(`/api/content/${id}`, fetcherApiRoute);
}
const fetcherApiRoute = (url: string): Promise<any> => {
return axios(url)
.then((r) => r.data)
.catch((err) => {
console.info('error is ', err)
throw err
});
};
export default useFetchContent;
api路由内部
export default async (req, res): Promise<ContentDetail> => {
const { id } = req.query;
if (req.method === 'GET') {
const fetchRealApi = await apiAxios(url);
if(fetchRealApi) {
// here depending on result of fetchRealApi i add some other fetch ...
return res.status(200).json({ ...fetchRealApi, complement: comp1 });
}
return res.status(500)
}
return res.status(500).json({ message: 'Unsupported method only GET is allowed' });
};
最后是 api axios 配置
const apiAxios = axios.create({
baseURL: '/myBase',
});
apiAxios.interceptors.request.use(
async (req) => {
// HERE i am trying to get token from cookies
// and also HERE if token is expired i am trying to refresh token
config.headers.Authorization = token;
req.headers['Content-type'] = 'application/x-www-form-urlencoded';
return req;
},
(error) => {
return Promise.reject(error);
},
);
export default apiAxios;
我被困在这里,因为我在 apiAxios.interceptors.request.use 期间找不到令牌... 你知道我做错了什么吗,我是否以正确的方式处理这种行为?
【问题讨论】:
-
这是否回答了您的问题:Why are cookies not sent to the server via getServerSideProps in Next.js??这个问题是关于
getServerSideProps,但同样适用于API 路由,你应该能够从req.headers['Cookie']的拦截器中获取token。