react-app中通过proxy解决跨域问题

版权声明:前端菜鸟--人间草木所有 https://blog.csdn.net/qq_43258252/article/details/88237482

proxy代理原理 是把本地 http://localhost:3000 端口的/api请求转发到了 代理服务器  比如 http://172.20.1.148:8082 

proxy代理 匹配   '/api'  的url

create-react-app 的版本高于 2.0 版本的时候在 package.json 只能配置 string 类型, 配置成如下: 

"proxy": "http://172.20.1.148:8082"

但是它只能匹配    '/api'  的url,而且只能匹配一个代理

如果你想代理多个,看下面

proxy代理 匹配   多个  的url

第一步:

安装 http-proxy-middleware 依赖

npm install --save-dev http-proxy-middleware

第二步:

在项目中 src 文件夹下新建文件 setupProxy.js ,写入如下代码

创建好这个文件之后,会自动的引用它,不需要额外的配置。不过代理想要生效,必须重新运行项目。

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

module.exports = function(app) {
  app.use(
    proxy('/back', {
      target: 'http://172.20.1.148:8082',
      changeOrigin: true
    })
  )
  app.use(
    proxy('/common', {
      target: 'http://172.20.1.148:8082',
      changeOrigin: true
    })
  )
}

提示!!!

提示:如果使用了axios请求拦截器的 配置 url,请注释掉     // conf.url = `${config.domain}${conf.url}`

 或者把  ${config.domain}  设为空    const testDomin = '' 

猜你喜欢

转载自blog.csdn.net/qq_43258252/article/details/88237482