node.js - 尝试代理请求时出错 (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
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));
}
我知道这个问题与服务器和应用程序没有同时运行有关,但我不知道可能出了什么问题。
解决方案
推荐阅读
- javascript - 数据插入后的谷歌工作表计算
- php - 在php打开和关闭之间点击输入时双换行符
- wordpress - Gutenberg:允许在 RichText 中进行其他格式设置
- c - 从 C 语言转换为 ARM 程序集——不断出现分段错误,与 ldr 和 str 混淆?
- android - React Native 导入 Facebook 图片
- powershell - Powershell 使用 UNC 路径在远程计算机上运行 exe
- html - Angular 6 未显示 HTML 解析错误
- javascript - 通过插入脚本标签调用 javascript 函数
- c++ - 使用标称值索引而不是字符串值
- c# - 如何从 rdlc 隐藏 rdlc word 和 excel 选项