美文网首页
React配置代理proxy(实现跨域请求)

React配置代理proxy(实现跨域请求)

作者: 莫伊剑客 | 来源:发表于2021-03-29 15:33 被阅读0次

    最近有不少伙伴询问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 proxy = require('http-proxy-middleware')
    
    module.exports = function (app) {
      app.use('/api', proxy( {
        target: 'http://172.16.136.249:8080',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          "^/api": ""
        }
      }))
    }
    

    然后运行项目

    yarn start
    // 或
    npm run start
    

    注意
    axios baseURL设置为‘/api’

    这样页面访问的时候/api就会替换成(http://172.16.136.249:8080)代理地址了!

    注意有些文章有坑

    const { proxy } = require('http-proxy-middleware')
    // 或
    // const proxy = require('http-proxy-middleware')
    
    module.exports = function (app) {
    // app.use(proxy('/api', { 这里的‘/api’应该是use的第一个参数,
      app.use(proxy('/api', {
    //正确写法 app.use('/api', proxy( {
        target: 'http://172.16.136.249:8080',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          "^/api": "/api"
        }
      }))
    }
    
    

    相关文章

      网友评论

          本文标题:React配置代理proxy(实现跨域请求)

          本文链接:https://www.haomeiwen.com/subject/nuebhltx.html