做网站最专业的公司/百度浏览器下载官方免费
最近有不少伙伴询问react的代理配置,自己也去试验了一下发现不少的坑,在这就将所遇到的坑和心得分享出来,希望能帮到更多的伙伴,避免踩坑。
1、 直接在package.json中设置proxy属性
这个是在用create-react-app脚手架搭建的react项目中的,可以直接在package.json中配置proxy:
有些文章里会提示以下方式
"proxy": {"/api/**": {"target": "http://172.16.136.249:8080","changeOrigin": true}}
当我们这样设置后,会报错
When specified, "proxy" in package.json must be a string.
Instead, the type of "proxy" was "object".
Either remove "proxy" from package.json, or make it a string.
error Command failed with exit code 1.
这是因为在新版本的react项目中,在package.json中的proxy只能设置成字符串,如下
"proxy": "http://172.16.136.249:8080"
配置后运行项目
yarn start
或
npm run start
由于package.json中,只能给proxy设置字符串;因此,这样的方式就导致,设置的代理只能配置一个,想要配置多个代理就不行了。
想要配置多的代理,请往下看
2、通过middleware中间件的方式设置proxy
在项目中安装middleware
yarn add http-proxy-middleware --save
或
npm install http-proxy-middleware --save
安装middleware插件后,在src目录中新建setupProxy.js文件,在文件中放入如下代码:
const { createProxyMiddleware } = require('http-proxy-middleware')module.exports = function (app) {app.use(createProxyMiddleware('/api', {target: 'http://172.16.136.249:8080',secure: false,changeOrigin: true,pathRewrite: {"^/api": "/api"}}))
}
然后运行项目
yarn start
或
npm run start
注意坑点
在有写文章会用proxy方式取值:
const { proxy } = require('http-proxy-middleware')
// 或
// const proxy = require('http-proxy-middleware')module.exports = function (app) {app.use(proxy('/api', {target: 'http://172.16.136.249:8080',secure: false,changeOrigin: true,pathRewrite: {"^/api": "/api"}}))
}
这的运行项目会报错,也是在纠结了很长时间后,在npm的网站中找到了http-proxy-middleware的设置方式:
这样就可以了
配置代理后的数据请求
这个交易的原url为/getdata,因为配置的代理增加了/api,就成了/api/getdata。
axios.post('/api/getdata').then((res) => {console.log('获取数据', res)}).catch(err => {console.log('数据请求失败', err)})
3、最后还想说下配置服务器代理或后端的core方式来进行跨域联调
配置代理就不用说了,Nginx的反向代理是除了名的优秀。
下边给出在node中的一种设置cors的方式,利用cors的中间件
1、在node的项目中安装cors的中间件
yarn add cors --save
或
npm install cors --save
2、 这个例子在express项目中,下边就给出在项目中的配置
const express = require('express')
const app = express()
const request = require('request')
const fs = require('fs')
// 跨域. CROS配置 ---------- Start
const cors = require('cors');app.use(cors({origin: ['http://172.16.136.249:3000'], // 所要允许跨域的ipmethods: ['GET', 'POST'],alloweHeaders: ['Conten-Type', 'Authorization']
}));
// 跨域. CROS配置 ---------- Endapp.post('/api/getdata', (req, res) => {let data = fs.readFileSync('./data/data.json')console.log('数据', data.toString())res.send(data.toString())
})app.listen(8080, () => {console.log('服务运行成功')
})
整体来看服务端配置跨域还是很方便的
本文引用: https://www.npmjs.com/package/http-proxy-middleware