package.json里设置多个代理报错proxy必须是string?

在create-react-app里想设置多个代理,
百度搜的写法都是在package.json里像这样写:

{
  "proxy":{
    "/api": {
      "target": "http://0.0.0.89:7300",
      "ws": true
    },
    "/foo": {
      "target": "http://0.0.11.22:8848",
      "ws": true
    }
  }
}

然后 npm 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! r-d-m@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1

求助,谢谢!!

阅读 15.6k
4 个回答

在package.json中查看你的react-scripts的版本号 版本太高可能不支持 把node_modules/react-scripts删除了 重新安装 npm i react-scripts@1.1.1 --save

在CRA2.X升级以后对proxy的设置做了修改,引用官方升级文档:

Object proxy configuration is superseded by src/setupProxy.js To check
if action is required, look for the proxy key in package.json and
follow this table:

I couldn't find a proxy key in package.json No action is required! The
value of proxy is a string (e.g. http://localhost:5000) No action is
required! The value of proxy is an object Follow the migration
instructions below. It's worth highlighting: if your proxy field is a
string, e.g. http://localhost:5000, or you don't have it, skip this
section. This feature is still supported and has the same behavior.

If your proxy is an object, that means you are using the advanced
proxy configuration. It has become fully customizable so we removed
the limited support for the object-style configuration. Here's how to
recreate it.

如果proxy的值是字符串,不需要修改

如果proxy的值是一个json,则需要做如下修改:

  1. npm install http-proxy-middleware
  2. src文件夹根目录下创建 setupProxy.js 文件
  3. package.json中的
"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/' }));
};

我已经找到解决方案,create-react-app 文档里面有解决方案http-proxy-middleware

新手上路,请多包涵

还有一种非常简单的方法

大概是这样

你在packge.json加入

"proxy": "http://0.0.0.89:7300"

然后你页面中的请求fetch('/api/userdata/')就会转发到proxy中的地址

也就是真实的请求是http://0.0.0.89:7300/api/userdata/,而且也不会有跨域问题

因为在浏览器看来,你只是发了fetch('/api/userdata/'),没有跨域问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏