持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情
跨域报错信息
如:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
方法一:在开发过程中向 API 服务器代理任何未知请求
在 package.json 中添加 proxy 字段
"proxy": "http://localhost:4000"
效果:可使用没有 text/html accept 标头的任何无法识别的请求都将被重定向到指定的 proxy(代理服务器)
注意事项:
proxy 只在开发环境中有效
确保对应的 URL 在生产环境中指向正确的地址
远程访问
proxy可在本地中使用,若在远程访问的话则会报错Invalid Host header,需要在项目根目录中名为.env.development的文件中指定公共开发主机:
HOST=mypublicdevhost.com
方法二:手动配置代理
在src/setupProxy.js中
yarn add http-proxy-middleware
创建 src/setupProxy.js
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api', { target: 'http://localhost:5000/' }));
};
注意事项
/api:就是识别的请求路径拼接,告诉请求,当请求携带/api时,需要用到这里跨域
target:需要跨域的网址
方法三:服务器启用CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD"); // 更新以匹配您将发出请求的域
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// 获取路由
});
app.post('/', function(req, res, next) {
// 处理路由
});
官网:CORS官网
方法四:定义永久环境变量
在项目的根目录中创建名为 .env 的文件
REACT_APP_SECRET_CODE=this
本文参考仅用于学习,如有错误理解请指出谢谢