跨域问题是前端开发中常见的问题,当你的前端应用尝试访问不同域名、端口或协议的API时就会出现。以下是几种解决方案:
1. 后端解决方案
CORS (推荐)
后端需要设置正确的响应头:
Access-Control-Allow-Origin: * // 或指定具体域名
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
2. 前端开发环境解决方案
开发服务器代理 (推荐)
在Vue/React等项目的配置文件中设置代理:
Vue CLI (vue.config.js):
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://your-api-server.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
React (package.json 或 webpack.config.js):
"proxy": "http://your-api-server.com"
3. 纯前端解决方案
JSONP (仅限GET请求)
axios.jsonp('http://example.com/api')
.then(response => {
console.log(response);
});
修改Axios请求配置
axios.get('http://example.com/api', {
headers: {
'Content-Type': 'application/json',
},
withCredentials: true // 如果需要携带cookie
})
.then(response => {
console.log(response);
});
4. 其他方案
浏览器插件
开发时可安装浏览器插件临时禁用同源策略(如Chrome的Allow CORS插件)
Nginx反向代理
生产环境可通过Nginx配置反向代理:
location /api/ {
proxy_pass http://your-api-server.com/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
注意事项
-
生产环境不要使用
Access-Control-Allow-Origin: *
,应指定具体域名 -
携带凭证(cookie等)时,后端需设置
Access-Control-Allow-Credentials: true
-
复杂请求(如Content-Type为application/json)会先发送OPTIONS预检请求
选择哪种方案取决于你的具体开发环境和项目需求。通常开发时使用代理,生产环境配置CORS是最佳实践。