create-react-app设置proxy反向代理不起作用

在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:

  1. I couldn't find a proxy key in package.json
    • No action is required!
  2. The value of proxy is a string (e.g. http://localhost:5000)
    • No action is required!
  3. 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/' }));
};