我目前正在开发一个使用 JWT 方法进行身份验证的 Next.js 13 应用程序。 我已经有一个现有的 Express 服务器,其中包含我需要的所有路由,我必须坚持使用这个服务器,直到我也将它移动到 Next.js。
我想做的是,每当我使用 axios 在服务器组件上发出请求时,附加保存在 cookie 中的 Bearer 令牌。
api.ts
import axios, { InternalAxiosRequestConfig } from "axios";
const API_URL = process.env.API_URL;
const api = axios.create({
baseURL: API_URL
});
api.interceptors.request.use(
(config: InternalAxiosRequestConfig<any>) => {
return config;
},
(error: any) => {
return Promise.reject(error);
}
);
export default api;
app/dashboard/page.tsx
const Dashboard = async () => {
const user = await me();
return (
<p>Dashboard</p>
);
};
me.ts
import api from "api";
const me = async () => {
try {
const { data } = await api.get("/auth/me");
return data;
} catch (err) {
throw err;
}
};
export default me;
我还有一个客户端组件“登录”,它向 /login 路由发送请求并取回 JWT,我这样保存它:
api.defaults.headers.common.Authorization = `Bearer ${token}`;
谢谢大家的帮助