首页 > 解决方案 > 尝试代理请求时出错 (ECONNREFUSED)

问题描述

这可能被标记为重复,但我查看了有关此主题的所有 Stack Overflow 帖子。我还在下面列出了其中一些。许多关于该主题的帖子也没有“勾选”正确答案。

我有一个 React 应用程序,我希望使用 Express 连接到 Node 服务器。这是我第一次这样做,所以我关注了这篇文章https://www.twilio.com/blog/react-app-with-node-js-server-proxy。我按照所有说明进行操作,据我所知,我已经检查了几次。所以我去研究,看看我能不能找出问题所在。

当我运行npm run dev启动服务器和 React 应用程序时,React 应用程序在我的浏览器中正确显示。但是,当我在文本框中输入我的名字时,我的终端中出现以下错误:

[HPM] Error occurred while trying to proxy request /api/greeting?name=Johnnie from localhost:3000 to http://localhost:3001/ (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

在前端的控制台中,我得到:

VM92:1 GET http://localhost:3000/api/greeting?name=Johnnie 504 (Gateway Timeout)
Uncaught (in promise) SyntaxError: Unexpected token E in JSON at position 0
Fetch failed loading: GET "http://localhost:3000/api/greeting?name=Johnnie.

我做了几个小时的研究,并按照以下 StackOverflow 帖子的说明进行操作:

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

获取 JSON 返回错误 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and status code 304: Not Modified

fetch 在 JSON 中给出响应 Unexpected token <

“React 代理错误:无法将请求 /api/ 从 localhost:3000 代理到 http://localhost:5000 (ECONNREFUSED)”?错误.. 没有在线解决方案

……和更多

我也添加了一个 setupProxy.js 文件。

这是我的包 .json 片段:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "server": "node-env-run server --exec nodemon | pino-colada",
    "dev": "run-p server start"
  },
  "proxy": "https://localhost:3001/",

我的 .env

REACT_APP_API_URL=http://localhost:3001

setupProxy.js

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

module.exports = function(app) {
    app.use(createProxyMiddleware("/api/*", { target: "http://localhost:3001/" }));
};

服务器/index.js

const express = require('express');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();
const PORT = 3001;

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

App.js 中的 handleSubmit 函数

  handleSubmit(event) {
    event.preventDefault();
    fetch(`/api/greeting?name=${encodeURIComponent(this.state.name)}`)
      .then(response => response.json())
      .then(state => this.setState(state));
  }

我知道这个问题与服务器和应用程序没有同时运行有关,但我不知道可能出了什么问题。

标签: node.jsreactjsexpress

解决方案


推荐阅读