如果我无法修改后端 CORS 配置时,可以使用以下方法:
方案1:开发代理(推荐):fire:
在开发环境中配置代理,将请求转发到目标服务器:
Vite 项目:
1 2 3 4 5 6 7 8 9 10 11 12
| export default { server: { proxy: { '/api': { target: 'https://api.example.com', changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, '') } } } }
|
Webpack/Create React App 配置:
1 2 3 4
| { "proxy": "https://api.example.com" }
|
方案2:使用 CORS 代理服务
利用第三方代理服务(仅用于开发测试):
1 2 3 4 5 6
| const proxyUrl = 'https://cors-anywhere.herokuapp.com/'; const targetUrl = 'https://api.example.com/data';
fetch(proxyUrl + targetUrl) .then(response => response.json()) .then(data => console.log(data));
|
:warning: 不建议在生产环境使用公共代理,存在安全和稳定性风险。
方案3:JSONP(仅支持GET请求)
如果后端支持 JSONP:
1 2 3 4 5 6 7 8 9 10 11
| function jsonp(url, callback) { const script = document.createElement('script'); script.src = `${url}?callback=${callback}`; document.body.appendChild(script); }
window.handleData = function(data) { console.log(data); };
jsonp('https://api.example.com/data', 'handleData');
|
方案4:搭建自己的代理服务器
使用 Node.js 创建简单的代理:
1 2 3 4 5 6 7 8 9 10 11 12 13
| const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api', createProxyMiddleware({ target: 'https://api.example.com', changeOrigin: true, pathRewrite: { '^/api': '' } }));
app.listen(3000);
|
方案5:浏览器插件(仅开发调试)
安装浏览器扩展如 “Allow CORS” 临时禁用浏览器的跨域限制,但这只在你本地有效。
生产环境建议
对于生产环境,最佳方案时:
- 使用 Nginx 或其他反向代理,将前端和后端放在同一域名下
- 云函数/Serverless 作为中间层转发请求
- 联系后端团队添加 CORS 支持(最根本的解决方案)
代理方式本质上是把跨域问题转移到服务器端,因为服务器之间的通信不受同源策略限制。