【问题标题】:Keep getting "Proxy error: Could not proxy request" error after adding proxy to react package.json添加代理以响应 package.json 后,不断收到“代理错误:无法代理请求”错误
【发布时间】:2020-03-05 18:34:18
【问题描述】:

我正在按照这个基本指南来设置一个本地开发环境,同时运行 react 和 node。在 react 目录的 package.json 添加 "proxy": "http://localhost:4001" 语句后我被卡住了。它一直说:代理错误:无法将请求 /flower 从 localhost:51427 代理到 http://localhost:4001

环境:不涉及身份验证。它只是一个样板 node.js 和 create-react-app 设置。 create-react-app 版本是 3.0.1。我使用的是 Mac。

我尝试了以下方法来解决这个问题:

  1. 我验证了服务器运行正常,并且 localhost:4001 确实提供了数据。
  2. 我检查了浏览器开发工具,发现错误是 GET http://localhost:51427/flower 500 (Internal Server Error)
  3. 我还在服务器的 package.json 中添加了一个“--ignore client”
  4. 我还尝试按照以下说明安装 http-proxy-middleware:https://create-react-app.dev/docs/proxying-api-requests-in-development/

这是 react 的 json 包:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-scripts": "3.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }, 
  "proxy": "http://localhost:4001"
}

react 的 localhost 页面是空白的,没有文字。控制台日志也确认没有收到任何数据。

【问题讨论】:

    标签: node.js reactjs proxy localhost


    【解决方案1】:

    尝试在 package.json 的代理配置中添加 "secure":false。

    package.json

    ... “代理”: { "/api": { "目标": "https://localhost:5002", “安全”:假 } }, ...

    参考链接: https://github.com/facebook/create-react-app/issues/3823

    【讨论】:

    • package.json 中的"proxy" 必须是字符串
    • 我收到此错误。指定时,package.json 中的“代理”必须是字符串。相反,“代理”的类型是“对象”。从 package.json 中删除“代理”,或将其设为字符串。
    • 如果您在遵循上述答案时收到错误,请参考以下stackoverflow question
    【解决方案2】:

    经过无数次搜索,我发现了问题并解决了问题!!!

    首先,由于当我在 react 上运行 npm 命令时出现代理错误,我认为我的 package.json 中的代理语句正在工作。由于我也可以通过 localhost:4001 到达服务器,问题一定是反应服务器以某种方式找不到 node.js 服务器,即不在同一个通信渠道等。

    然后我搜索并发现问题与它们没有同时运行有关(我还考虑了其​​他可能性,比如一个在 ipv4 上运行,另一个在 ipv6 上运行,但这个似乎是最有可能的解决方案)。这个答案帮助我弄清楚如何实现它:Could not proxy request /pusher/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED)

    但是并发请求会失败,因为当它尝试运行客户端时,它会失败,因为端口总是会被阻塞。例如,当我运行“npm start --prefix client”时,即使我更改了 package.json 中的端口,它总是会报告“在端口 XXX 上运行的东西”。然后我发现问题必须没有为我的本地主机设置正确的配置,这个答案帮助了我:npm start reports "Something is already running on port XXX" no matter what XXX is

    现在并发,终于可以工作了。

    【讨论】:

    • 能否请您发布最终为您工作的配置
    猜你喜欢
    • 2022-07-05
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 2018-08-19
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多