Next.js14中Axios实例Authorization不生效,是否需手动传token?
问题解答
1. 是否需要在每个请求中手动设置Authorization?
不需要,完全可以通过Axios的拦截器机制统一处理,避免重复编写相同代码。
2. 正确的做法是什么?
你的问题根源在于服务器端创建Axios实例时,无法直接获取请求上下文的cookie:在Next.js 14的App Router Route Handler中,getCookie函数需要传入当前的request对象才能在服务器端读取到cookie,而你在创建Axios实例时直接调用getCookie("user"),此时没有请求上下文,导致token无法被正确获取,Authorization头自然无效。
推荐通过Axios请求拦截器动态设置Authorization头,同时兼容客户端和服务器端环境:
步骤1:修改Axios实例,添加请求拦截器
import axios from "axios"; import { apiBaseURL } from "config"; import { getCookie } from "cookies-next"; export const axiosServerBase = axios.create({ baseURL: apiBaseURL, timeout: 30000, }); // 请求拦截器:每次请求前动态设置Authorization头 axiosServerBase.interceptors.request.use( (config) => { // 从自定义参数中获取当前请求对象(仅服务器端Route Handler中需要) const request = config.customParams?.request; let authToken; if (request) { // 优先从客户端请求的headers中提取Authorization(透传逻辑) authToken = request.headers.get("authorization"); if (!authToken) { // 若headers中没有,再尝试从服务器端cookie读取 const userCookie = getCookie("user", { req: request }); authToken = userCookie ? `Bearer ${JSON.parse(userCookie as string).token}` : undefined; } } else { // 客户端环境直接从cookie读取 const userCookie = getCookie("user"); authToken = userCookie ? `Bearer ${JSON.parse(userCookie as string).token}` : undefined; } if (authToken) { config.headers.Authorization = authToken; } return config; }, (error) => Promise.reject(error) );
步骤2:在Route Handler中使用时传递请求对象
import { axiosServerBase } from "config"; export async function POST(request: Request): Promise<Response> { try { const body = await request.json(); const { data } = await axiosServerBase.post( "/templates/save-email-template", { data: body }, { // 将当前请求对象传递给拦截器 customParams: { request } } ); return Response.json({ status: 200, data }); } catch (error: any) { return Response.json({ status: 400, message: error.response?.data?.message || "请求失败", }); } }
简化方案(仅透传客户端Authorization头)
如果你的后端API只需要验证客户端传来的token,无需从服务器端cookie读取,可简化拦截器逻辑:
axiosServerBase.interceptors.request.use( (config) => { const request = config.customParams?.request; if (request) { const authHeader = request.headers.get("authorization"); if (authHeader) { config.headers.Authorization = authHeader; } } return config; }, (error) => Promise.reject(error) );
这样就能实现统一设置Authorization头,无需在每个请求中手动处理。
内容的提问来源于stack exchange,提问作者Mazen Ahmed
相关产品推荐
相关产品推荐

