When specified, “proxy” in package.json must be a string.

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.

配置React跨域时候

在网上看到是这样配置的,在package.json里添加如下代码

"proxy": {
  "/api": {
    "target": "http://localhost:5000"
    },
  
}

但是启动项目却报上面那个错误

以为我哪里写的不对,一个一个字对比,发现没毛病啊

于是在网上搜了下错误代码

在Facebook官方github里看到了

原来React新版本不支持那样设置反向代理了


新版本需要这样做

安装http-proxy-middleware

$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware

然后

在创建一个setupProxy.js文件,在src目录,src/setupProxy.js

例如之前的配置

"proxy": {
  "/api": {
    "target": "http://localhost:5000/"
    },
  "/*.svg": {
    "target": "http://localhost:5000/"
  }
}

setupProxy.js文件里则这样写

const proxy = require('http-proxy-middleware')
 
module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:5000/' }))
  app.use(proxy('/*.svg', { target: 'http://localhost:5000/' }))
}

完整的写法

app.use(proxy('/api', { 
target: 'https://localhost:5000/',
changeOrigin:true,
pathRewrite: {
            "^/api": "/"
        }
 }))

更多问题看:https://github.com/facebook/create-react-app/issues/5103

评论

回复 ga 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注




Enter Captcha Here :