react解决跨域的几种方案附源码下载
日期:2019-11-07
来源:程序思维浏览:1609次

官网react脚手架,配置跨域的方式有出现了“proxy” in package.json must be a string下面来看看如何解决吧...
需要在package.json里配置下proxy。OK,照着大神的分享一步一步配置好了。却提示:

照字面意思来理解。。proxy必须是一个字符串,但是我配置的是对象。
方法1:那就按照字符串来配置。

使用:

需要注意的是,get方法里的url路径无需写本地服务器地址了,也就是说所有的请求都会走这里。
方法2:http-proxy-middleware 插件。
$ npm install http-proxy-middleware --save
$ 或
$ 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:80' }));
// app.use(proxy('/test', { target: 'http://localhost:3000' }));
// 省略...
};
需要注意的是,该文件无需在任何地方引入,重新启动项目(npm start)即可。
另外‘/api’意思是碰到这个开头的路径就会走上面的target地址。就是拼接起来的感觉,如:

相当于http://localhost:80/api/react/header.json。
需要注意的是,/api也会拼接上去,如果你的路径没有这个单词,可以使用完整的配置,如下:
app.use(proxy('/api', {
target: 'http://localhost:80',
changeOrigin:true,
pathRewrite: {
"^/api": "/" // 把/api 变成空
}
}));
相当于http://localhost:80/react/header.json。
跑起来大概是这样子。

方法3:配置webpack的proxy
找到config/webpackDevServer.config.js大约84行将proxy注释掉改成:
proxy:{
"/api":{
target:"http://vueshop.glbuys.com/api",
changeOrigin:true,//支持跨域
pathRewrite:{
'^/api':""
}
}
}
这样就解决跨域了。
以上就是react解决跨域的几种方法。
源码下载
精品好课