Nuxt中useFetch/$fetch携带Cookie始终返回401问题求助
问题分析
核心问题出在Nuxt中间层(server/api/sn/index.ts)的请求逻辑上:
- 前端调用
/api/sn时,credentials: "include"会把浏览器的Cookie传给Nuxt服务器,但Nuxt服务器发起的$fetch请求到localhost:5050时,不会自动携带前端的Cookie——服务器端请求的Cookie上下文和浏览器完全独立。 - Postman能正常请求是因为你手动把Cookie放在了请求头里,而Nuxt中间层没做这个传递动作。
解决方案
修改Nuxt中间层的代码,将前端请求过来的Cookie手动传递给后端localhost:5050的接口。
修改后的代码
server/api/sn/index.ts
import type { SerialNumbers } from "~/types/serialnumber"; import { getRequestHeader } from 'h3'; export const allSN: SerialNumbers = []; const apiBaseUrl = "http://localhost:5050"; export default defineEventHandler(async (event) => { // 从前端请求中获取Cookie头 const cookieHeader = getRequestHeader(event, 'cookie'); if (allSN.length) { return { allSN, }; } const _allSN: [] = await $fetch(`${apiBaseUrl}/serialnumber`, { headers: { // 将前端的Cookie传递给后端服务 ...(cookieHeader && { Cookie: cookieHeader }) } }); allSN.push(..._allSN); if (!allSN) { throw createError({ statusCode: 404, message: "Data not fetched.", }); } return { allSN, }; });
关键注意点
- 确保后端
localhost:5050的CORS配置中,除了ALLOWED_ORIGINS,还设置了Access-Control-Allow-Credentials: true——这是允许跨域携带Cookie的必要配置。 - 移除
$fetch中的credentials: "include":服务器端请求不需要这个配置,它只对浏览器环境的请求生效。
内容的提问来源于stack exchange,提问作者M Hasan Nudin
相关产品推荐
相关产品推荐

