使用带有React-Scripts版本3.4.1的Create React App代理多个API请求

时间:2020-04-28 04:02:31

标签: reactjs create-react-app react-scripts

我当前正在使用旧版本的React Script 1.5.1。我想升级我的react应用(react-scripts v 3.4.1),但是这样做会破坏package.json中定义的代理结构。

我当前的JSON具有

"proxy": {
  "/ossapi": {
    "target": "http://localhost:8002"
  },
  "/pcp": {
    "target": "http://test.corp.test.com:8004"
  },
  "/ossOps": {
    "target": "http://test.corp.test.com:8085"
  },
  "/ems": {
    "target": "http://test.corp.test.com:8001"
  }
}

即使我升级到新的React-scripts版本3.4.1之后,我也希望为我的应用程序设置类似的设置,因为我已经做了很多开发,并且不想再次从头开始。 当我将react-scripts版本更改为最新的稳定版3.4.1时,它会不断抛出无法解析json错误的信息。

请告知。

以下是我得到的错误:

npm ERR! code EJSONPARSE
npm ERR! file /Users/dhrumit.sheth/Documents/Dev/stash/console-app/package.json
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected token } in JSON at position 1438 while parsing near '...git push --tags",
npm ERR! JSON.parse   },
npm ERR! JSON.parse "proxy": [
npm ERR! JSON.parse   "/os...'
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just JavaScript.

1 个答案:

答案 0 :(得分:0)

我相信package.json中的

“ proxy”适用于单个端点。要进行更高级的配置,您需要在项目根文件夹中创建setpProxy.js文件,安装http-proxy-middleware并将配置放在此处。代码将如下所示。

module.exports = function(app) {
  app.use(
    '/ossapi',
    createProxyMiddleware({
      target: 'http://localhost:8002',
      changeOrigin: true,
    })
  );
  app.use(
    '/pcp',
    createProxyMiddleware({
      target: 'http://test.corp.test.com:8004',
      changeOrigin: true,
    })
  );
};

和其他一样。 documentation在这里。