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

react项目在package.json中配置proxy之后,报错

$ npm run start

> img@0.1.0 start D:\xx\src\img
> react-scripts start

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.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! img@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the img@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xx\AppData\Roaming\npm-cache\_logs\2019-09-11T08_04_08_822Z-debug.log

原因是react-scripts模块中从2开始改变了proxy的配置方式,解决的方法有两种

第一种方式是,指定安装react-scripts的老版本

1.删除node_modules/react-scripts

2.重新安装 npm i react-scripts@1.1.1 --save

 

第二种方式是,使用新版本proxy的配置方法

1.安装http-proxy-middleware

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

2.src目录下新建文件:setupProxy.js,配置代码为:

const proxy = require('http-proxy-middleware')
 
module.exports = function(app) {

  app.use(proxy('/api', 
    {
        "target": "https://localhost:5000/",
        "changeOrigin": true
    }))
    
    //app.use(proxy(...)) //可以配置多个代理
}

 

posted on 2019-09-11 16:12  Netsharp  阅读(5133)  评论(0编辑  收藏  举报

导航