react项目添加代理解决跨域

在src文件夹下添加setupProxy.js文件

setupProxy.js(新)axios不能配置baseURL:

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
    '/edu',
    createProxyMiddleware({
      target: 'http://test_zhiliao.gongzuoshouji.cn',
      changeOrigin: true,
    })
  )
}

setupProxy.js(旧):

const proxy = require('http-proxy-middleware')

module.exports = function(app) {
  app.use(
    proxy('/api', {
      target: 'http://localhost:85',
      secure: false,
      changeOrigin: true,
      pathRewrite: {
        "^/api": "/api"
      }
    })
  )
}

重启,项目即可。

注意,axios默认请求地址不要改。对前端来说,接口就好像是在3000端口一样,根本察觉不到配置了代理。

原文地址:https://www.cnblogs.com/xutongbao/p/14876292.html