Set multiple agents to report errors in package.json. Proxy must be string?.

you want to set up multiple proxies in create-react-app.
Baidu search is written in package.json like this:

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

then npm start reports an error

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

ask for help, thank you!


check the version number of your react-scripts in package.json may not support removing node_modules/react-scripts and reinstalling npm I react-scripts@1.1.1-- save


change the settings of proxy after the CRA2.X upgrade, refer to the official upgrade document:

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 allowed! The
value of proxy is a string (requests http://localhost:5000) No action is
qualified! The value of proxy is an object Follow the migration
instructions below. It's worth highlighting: if your proxy field is a
string, customers 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.

if the value of proxy is a string, you do not need to modify

if the value of proxy is a json, you need to make the following modifications:

  1. npm install http-proxy-middleware
  2. create a setupProxy.js file under the root of the src folder
  3. in package.json
"proxy": {
      "/api": {
        "target": "http://localhost:5000/"
        },
      "/*.svg": {
        "target": "http://localhost:5000/"
      }
    }

migrate to 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/' }));
};

I have found the solution. There is a solution http-proxy-middleware in the create-react-app document


there is also a very simple method

something like this

you add

to packge.json
"proxy": "http://0.0.0.89:7300"

then the request fetch ('/ api/userdata/') on your page will be forwarded to the address in proxy

that is, the real request is http://0.0.0.89:7300/api/userdata/, and there will be no cross-domain problems

because from the browser's point of view, you only sent fetch ('/ api/userdata/') without cross-domain problems

Menu