create-react-app 和节点服务器的 ECONNREFUSED 错误

2023-12-09

我正在使用 create-react-app (因此没有自定义 webpack)和节点服务器构建 MERN 应用程序。我正在使用 nodemon 重新启动后端上的更改,问题是大约一半的时间似乎我的前端尝试在 nodemon 重新启动节点服务器之前进行渲染,从而导致 ECONNREFUSED 错误。

我只需刷新页面即可解决问题,但必须重复执行此操作很烦人,我想弄清楚问题可能是什么。如果我运行节点服务器而不是nodemon,则不会发生这种情况。

这是我的客户端 package.json 的相关部分:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
},
"proxy": "http://localhost:7777"

和服务器端package.json:

"scripts": {
   "client-install": "npm intall --prefix client",
   "start": "node server.js",
   "server": "nodemon server.js",
   "client": "cd client && npm start",
   "dev": "concurrently \"npm run server\" \"npm run client\""
}

和我的 server.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const routes = require('./routes/index');
require('dotenv').config();

const app = express();

app.use(bodyParser.json());

mongoose.connect(process.env.DATABASE, {useNewUrlParser: true})
    .then(() => console.log('MongoDb connected'))
    .catch(err => console.log(`Mongo error ${err}`))

const port = process.env.PORT || 7777;

app.use('/', routes);

if (process.env.NODE_ENV === 'production') {
    // Serve any static files
    app.use(express.static(path.join(__dirname, 'client/build')));
    // Handle React routing, return all requests to React app
    app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    });
}

app.listen(port, () => {
    console.log(`Connected at port ${port}`)
})

我使用 axios 来处理前端 HTTP 请求:

import axios from 'axios';
import FormData from 'form-data'
import keys from '../keys';

export const getPosts = () => {
    return axios.get('/api')
}
export const post = (file, bodyInfo) => {
    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    formData.append('bodyInfo', JSON.stringify(bodyInfo));
    return axios.post('/api', formData, {
        headers: {
            'Content-Type': `multipart/form-data; 
              boundary=${formData._boundary}`,
          }
    })
}
export const getSinglePhoto = (id) => {
    return axios.get(`/api/${id}`);
}
export const postUser = (userDetails) => {
    console.log(userDetails);
    return axios.post('/api/user', userDetails)
}
export const getUser = () => {
    return axios.get('/user');
}
export const removeUser = (id) => {
    return axios.delete(`/user/${id}`)
}

这是我的路线:

router.get('/api', postController.getPosts);
router.post('/api', 
    postController.type, 
    postController.uppic,
    postController.cloudinary
);
router.get('/api/:id', postController.getSingle);
router.get('/user', userController.getUser);
router.post('/api/user', userController.postUser);
router.delete('/user/:id', userController.removeUser);

尝试使用CORS代替package.json代理人。我记得当我使用它时遇到了随机/间歇性连接问题。简而言之:前端在端口上运行3000 and expressAPI 运行于5000。编译后,两者都运行在5000 and express为编译后的前端js提供服务,其作用类似于API。

设置非常相似,但没有连接问题:

快递服务器package.json

...
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "NODE_ENV=production node app.js",
    "server": "NODE_ENV=development nodemon app.js",
    "client": "npm run start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "seeds": "NODE_ENV=development node seeds.js"
},
...

客户端/package.json(使用 sass 编译器,您可以使用/忽略)。

...
"scripts": {
    "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
    "start-js": "react-scripts start",
    "start": "npm-run-all -p watch-css start-js",
    "build": "npm run build-css && react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
},
...

客户端/src/actions/axiosConfig.js(然后我创建一个axios配置自动指向我运行的 Express API5000)

import axios from 'axios';

export const app = axios.create({
    baseURL: 'http://localhost:5000/api/',
    withCredentials: true
})

客户端/src/actions/authActions.js(然后导入axios config)

import { app } from './axiosConfig';

const signinUser = props => dispatch => (
    app.post(`signin`, { ...props })
    .then(({data}) => {
        dispatch({ type: types.SET_SIGNEDIN_USER, payload: data })
        dispatch(fetchAvatarOnLogin());
    })
    .catch(err => dispatch({ type: types.SERVER_ERROR, payload: err }))
);

快递服务器.js (I use consign导入所有文件):

const express   = require('express');
const app       = express();
const consign   = require('consign');

consign({ locale: 'en-us', verbose: false})
    .include('libs/middlewares.js')
    .then("database")
    .then("shared")
    .then("services")
    .then("controllers")
    .then("routes")
    .then('libs/server.js')
    .into(app);

然而,等价的是:

// APP REQUIRED IMPORTS
const express   = require('express');
const app       = express();
...etc

// APP MIDDLEWARES
...
app.use(cors({credentials: true, origin: http://localhost:3000})) // allows receiving of cookies from front-end
app.use(morgan('tiny')); // logging framework
app.use(bodyParser.json()); // parses header requests (req.body)
app.use(bodyParser.urlencoded({ extended: true })); // allows objects and arrays to be URL-encoded
...etc

// DATABASE CONFIG/CONN


// APP SHARED FUNCS


// APP SERVICES (passport, sendgrid mailer, ...etc)


// APP CONTROLLERS
...
signin: (req, res, done) => passport.authenticate('local-login', err => (
        (err || !req.session) ? sendError(err || badCredentials, res, done) : res.status(201).json({ ...req.session }))
    )(req, res, done)
...etc

// APP ROUTES
...
app.post('/api/signin', signin);
...etc

// EXPRESS SERVER
if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));   

    app.get('*', (req, res) => res.sendFile(path.resolve('client', 'build', 'index.html')));
}

app.listen(5000);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

create-react-app 和节点服务器的 ECONNREFUSED 错误 的相关文章

随机推荐

  • 如何推迟内联Javascript?

    我有以下 html 代码
  • 停止模式 UIViewController 旋转

    模态UIViewController的父级自动旋转 但是当模态 VC 启动时 我只希望它以纵向显示而不是可旋转 我试过简单地返回 NOshouldAutorotate 在模态VC中 但没有欢乐 支持 iOS 5 非常感谢任何帮助 基本上 如
  • 如何创建类似于 Xcode 属性面板的选项卡式面板

    我正在尝试创建一个类似于 Xcode 属性面板的选项卡式面板 但标准选项卡式面板似乎具有不同的外观和感觉 无法更改它 应使用哪些控件来创建外观相似的选项卡式面板 编辑 我没有使用 NSTabViewController 只是有 TabVie
  • Mongo 用户定义函数和 MapReduce

    mongodb 有没有办法创建用户定义的 Javascript 函数 我在客户端有几个 Map Reduce 函数 我想在其他 MR 函数中使用它们 例如 多个 MR 函数可以计算各种平均值 我希望能够像这样使用它们 function re
  • TypeScript 装饰器和循环依赖

    考虑使用装饰器的相互依赖代码示例 如下 现在考虑以下工作流程 是的 我确实想传递实际导出的类 因为我稍后需要使用它们 应用程序导入并运行Parent ts Test Child 导致应用程序导入Child ts装修时 注 班级Parent代
  • 合并来自 git 存储库外部的更改

    我正在与该国另一边的另一位开发人员合作 他是我们项目的负责人 并且没有使用正式的版本控制系统 就我而言 我正在 git 中跟踪我的所有代码 我最近开始为主项目做出贡献 并且也希望能够跟踪其他开发人员的更新 当我收到他更新的代码时 它通常是
  • 在应用 LIMIT 之前获取结果计数的最佳方法

    当对来自数据库的数据进行分页时 您需要知道将有多少页来呈现页面跳转控件 目前我通过运行查询两次来做到这一点 一次包装在count 确定总结果 第二次应用限制以仅返回当前页面所需的结果 这看起来效率很低 有没有更好的方法来确定之前会返回多少结
  • opencv中的缩放和旋转模板匹配

    I want to use a template image to search target in the another image But the target have scale and rotation change also
  • 使用 jquery 预加载图像数组

    我正在使用 jQuery 从 php 数组构建图像数组 我想循环浏览这些图像 预加载它们 同时显示一些加载 gif 直到加载所有图像 目前 我已经尝试了很多方法来这样做 页面的其余部分似乎总是在继续加载 因此图像正在被预加载 但不是在页面加
  • ApplicationInsights OperationId 为空

    我正在实现自定义 ApplicationInsights 记录器 并且能够在跟踪 异常和请求等写入位置写入所有日志 但跟踪和异常中的 OperationId 为空 昨天我使用相同的代码并在所有表中获取OperationId 之后我玩了多线程
  • Rails 从 JSON 数组中选择

    我有一个从 Foursquare 返回的 JSON 数组 我们就这样称呼它吧 venues 我希望能够通过下拉框 选择 场地 并且我希望它成为表单的一部分 这意味着我希望能够按名称选择特定场地 即本例中为 Hotel Utah Saloon
  • 关于使用 Installshield 2013 (.issuite) 项目文件生成的 Setup.exe 进行静默安装

    我有一个使用 installshield 套件项目 issuite 文件生成的 setup exe 文件 对于具有足够权限的管理员或普通用户 我们的 IT 管理员之一可以使用以下命令进行静默安装 setup exe silent 但是 当尝
  • 按本地化排序列表

    我需要排序一个List
  • 通过jquery获取对象数组的索引

    我有以下数组 var array id aa description some description id bb description some more description id cc description a lot of d
  • 在 OSX Yosemite 上的 Emacs 中使用 LLVM 调试器

    我想知道是否可以将 LLVM 调试器与 Emacs 一起使用 例如M x gdb接口标准 提前致谢 令人惊讶的是 向 Emacs 添加 LLVM 调试器支持是有争议的 或者没有争议 取决于您的愤世嫉俗程度 2015年2月 理查德 斯托曼写道
  • 操作系统导致的 irq 延迟是多少?

    如何估计 ARM 处理器上的 irq 延迟 irq 延迟的定义是什么 中断请求 irq 延迟是中断请求从中断源传输到被服务点所需的时间 因为有不同的中断通过不同的路径来自不同的源 显然它们的延迟取决于中断的类型 您可以找到有关特定中断的延迟
  • web.config 中的 C# 命名空间

    来自 VB 背景并被迫学习 C 的我遇到了第一个障碍 在 VB 中 我可以将我想要在整个应用程序中可用的所有命名空间放入 web config 文件中 并且它将在每个代码隐藏文件中可用 而无需添加导入语句
  • 在单体 SpringBoot 应用程序中创建集成测试

    我被要求为一个非常大的 SpringBoot 项目中的一个服务创建一个集成测试 该项目产生了数十个已实现的服务 执行应用程序时 会部署所有这些服务 我想避免部署与我正在为其创建测试的服务无关的所有服务 不幸的是 我 还 没有像我希望的那样有
  • ViewBox 使 RichTextBox 失去插入符

    RichTextBox 放置在 ViewBox 内并缩放至 10 1000 的各个级别 当百分比小于 100 时 插入符号会在随机光标位置消失 我知道当视觉效果被缩小 压缩 时 它会丢失像素 有什么办法可以让我不再丢失光标吗
  • create-react-app 和节点服务器的 ECONNREFUSED 错误

    我正在使用 create react app 因此没有自定义 webpack 和节点服务器构建 MERN 应用程序 我正在使用 nodemon 重新启动后端上的更改 问题是大约一半的时间似乎我的前端尝试在 nodemon 重新启动节点服务器