【问题标题】:Proxying Multiple API requests with Create React App with React-Scripts version 3.4.1使用带有 React-Scripts 版本 3.4.1 的 Create React App 代理多个 API 请求
【发布时间】:2020-04-28 04:02:31
【问题描述】:

我目前使用的是旧版本的 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 时,它不断抛出 failed to parse 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.

【问题讨论】:

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


    【解决方案1】:

    package.json 中的“代理”适用于我相信的单个端点。对于更高级的配置,您需要在项目根文件夹中创建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这里。

    【讨论】:

    • 感谢您的回复。但是在多个proxy和target的情况下,我们是传对象还是数组呢?
    • 你不传递数组或对象@Mave7。我已经针对您的用例修改了我的答案。请看看它是否有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2020-08-04
    • 2019-04-26
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多