但是如果访问的接口跨域了,这一行为就会被禁止掉,
为了解决这个问题(浏览器识别的跨域问题),
就需要设置反向代理,把后端的服务 虚拟的部署到前端本地。
举例:接口的地址为192.111.111.111:3000/api/xxxx
前端的地址为本地:localhost:8000
那就需要把后端的接口地址转到:localhost:8000/api/xxxx
就解决了跨域的问题了。
下面是具体的解决方式:
在项目中安装middleware
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"
}
}))
然后运行项目
注:所有的前提都在后端允许跨域的情况下才可行!
参考:https://blog.csdn.net/jason_renyu/article/details/104640965