尝试代理请求时出错(ECONNREFUSED)

时间:2020-09-29 09:30:11

标签: node.js reactjs express

这可能被标记为重复,但是我查看了有关此主题的所有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

Fetching JSON returns error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and status code 304: Not Modified

fetch gives response Unexpected token < in JSON

"React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:5000 (ECONNREFUSED)'? Error.. No solution online

……还有更多

我也添加了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/" }));
};

server / 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));
  }

我知道问题与服务器和应用程序无法同时运行有关,但我不知道这可能是错的。

0 个答案:

没有答案