Vue.js中使用Fetch发送带自定义Header的GET请求时出现CORS错误
问题解决方案:CORS自定义请求头被拦截
核心结论
这是服务器端问题,前端无法绕过浏览器的CORS安全限制,必须通过服务器配置解决。
为什么Postman能成功,浏览器不行?
Postman不属于浏览器环境,不会触发CORS预检机制;而浏览器在发送包含自定义请求头(如language)的请求前,会先发送一个OPTIONS预检请求,要求服务器明确允许该自定义头。如果服务器的预检响应中Access-Control-Allow-Headers没有包含language,浏览器就会拦截后续的实际请求,抛出你看到的错误。
前端代码修正
你在请求头里添加的"Access-Control-Allow-Headers": "X-Custom-Header"是错误的——这个头是服务器响应头,不是请求头,直接删掉这行:
const result = await fetch('url', { method: 'GET', headers: { 'Content-Type': 'application/json', 'language': 'en' } });
服务器端配置步骤
根据你的服务器类型,添加以下配置,确保language被加入Access-Control-Allow-Headers列表:
1. Node.js + Express(使用cors中间件)
const cors = require('cors'); const express = require('express'); const app = express(); // 配置允许的请求头与源 app.use(cors({ allowedHeaders: ['Content-Type', 'language'], origin: 'http://localhost:8080' // 建议指定具体源,而非通配符* }));
2. Nginx
在对应location块中添加:
location / { add_header Access-Control-Allow-Origin http://localhost:8080; add_header Access-Control-Allow-Methods GET, POST, OPTIONS; add_header Access-Control-Allow-Headers Content-Type,language; # 处理OPTIONS预检请求 if ($request_method = OPTIONS) { return 204; } }
3. Java Spring Boot(全局CORS配置)
创建全局配置类:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8080") .allowedMethods("GET", "POST", "OPTIONS") .allowedHeaders("Content-Type", "language"); } }
验证
配置完成后重启服务器,再用前端发送请求,浏览器会通过预检并正常获取响应。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

