尝试代理到 M1 Macbook 上的 localhost:3000/api 时发生错误

noB*_*ody 7 node.js reactjs apple-m1

我正在开发一个使用 Node.js、React.js 和 MongoDB 的项目。

当我向服务器发送请求时,出现以下错误:

尝试代理/api/auth/login来自localhost:3000http://localhost:6000(ECONNRESET) 的请求时发生错误。

我的客户端在端口 3000 上运行,服务器在本地端口 6000 上运行。这是客户端代理中间件设置代码:

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/api/", { target: "http://localhost:6000", "secure": "false" }));
};
Run Code Online (Sandbox Code Playgroud)

我尝试过使用127.0.0.1inplace of localhost,但没有成功。

该项目在 Windows 笔记本电脑上运行良好。但是,M1 Mac 出现问题。

任何指导都会对我有很大帮助。

Via*_*lav 14

我使用 M1 时遇到了同样的错误。

这段代码开始对我正常工作。

http://localhost:3000/->http://127.0.0.1:3000/

服务器.js

"use strict";

const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const PORT = 9090;
const HOST = "0.0.0.0";

const app = express();

app.use(
  createProxyMiddleware("/", {
    target: "http://127.0.0.1:3000/",
  })
);

app.listen(PORT, HOST);

Run Code Online (Sandbox Code Playgroud)

包.json


{
  "name": "web",
  "version": "1.0.8",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6"
  }
}
Run Code Online (Sandbox Code Playgroud)
  • 节点 v18.11.0
  • npm 8.19.2

服务器位于“http://127.0.0.1:3000/” - create-react-app的默认配置(“react-scripts”:“^5.0.1”)


noB*_*ody 5

我将 Node.js 的版本更改为 14.9.0 并且它有效。

以下是在互联网上找到的对我不起作用的解决方案:

  • 将 node.js 版本更改为其他稳定版本 16 或 18
  • 在服务器上指定这样的 IPv4 地址(因为我可以看到我的服务器在 IPv6 上运行):server.listen(13882, "0.0.0.0", function() { });
  • 从 Package.json 文件中删除代理条目
  • 更新为{target: "http://localhost:6000/"}OR {target: "https://localhost:6000/"}OR {target: "http://127.0.0.1:6000"}OR {'http://[::1]:6000'}OR{app.use(proxy("/api/", {target:"http://localhost:6000",secure: false,changeOrigin: true}));}

我在 package.json 文件中有此条目"proxy": "http://localhost:6000"

这是我的 setupProxy.js 文件

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/api/", { target: "http://localhost:6000" }));
};
Run Code Online (Sandbox Code Playgroud)