React项目对接后端遭遇CORS策略拦截问题求解
解决Create React App中的CORS问题(无法修改服务器时)
你遇到的两个CORS错误本质如下:
问题1:
Access to XMLHttpRequest at 'https://localhost:7022/Leads/106/status' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.浏览器发起的OPTIONS预检请求未得到200系列响应,导致后续请求被拦截。
问题2:
Access to XMLHttpRequest at 'https://localhost:7022/Leads/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.服务器未返回允许跨域的
Access-Control-Allow-Origin响应头。
由于无法修改服务器配置,可采用以下方案解决:
1. 利用Create React App内置代理(开发环境)
- 在项目根目录的
package.json中添加一行配置:"proxy": "https://localhost:7022" - 修改前端请求代码,去掉域名前缀,直接请求相对路径:
// 原请求:fetch('https://localhost:7022/Leads/106/status') fetch('/Leads/106/status') - 重启开发服务器后,代理会自动将前端请求转发到后端,规避跨域限制。
2. 开发环境临时禁用浏览器CORS限制
仅用于本地测试,禁止用于日常浏览:
- Windows:关闭所有Chrome窗口后,执行命令:
chrome.exe --disable-web-security --user-data-dir="C:/ChromeDevSession" - Mac:关闭所有Chrome窗口后,执行命令:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --disable-web-security --user-data-dir="/tmp/chrome_dev" - 启动后浏览器会提示“您使用的是不受支持的命令行标记”,此时跨域限制已关闭。
3. 使用http-proxy-middleware实现灵活代理(开发环境)
适合需要多代理规则的场景:
- 安装依赖:
npm install http-proxy-middleware --save-dev - 在项目
src目录下创建setupProxy.js文件:const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/Leads', createProxyMiddleware({ target: 'https://localhost:7022', changeOrigin: true, secure: false // 若后端使用自签名HTTPS证书,需添加此配置 }) ); }; - 修改请求为相对路径,重启开发服务器即可生效。
4. 生产环境解决方案
部署上线时,需在前端部署服务器(如Nginx)配置反向代理:
- 以Nginx为例,在配置文件中添加:
location /Leads { proxy_pass https://localhost:7022; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } - 前端请求仍使用相对路径,Nginx会将请求转发到后端,避免跨域。
内容的提问来源于stack exchange,提问作者Arthur Hauck Dittz
相关产品推荐
相关产品推荐

