create-react-app設置proxy反向代理不起做用

在CRA2.X升級之後對proxy的設置作了修改,引用官方升級文檔:npm

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

  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.api

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.app

若是proxy的值是字符串,不須要修改svg

若是proxy的值是一個json,則須要作以下修改:ui

1. npm install http-proxy-middlewarethis

2. src文件夾根目錄下建立 setupProxy.js 文件spa

3. package.json中的code

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

遷移到setupProxy.js中blog

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/' }));
};
相關文章
相關標籤/搜索