【问题标题】:React/Express App - API Requests to Backend Proxy error: Could not proxy request (ECONNRESET)React/Express App - API Requests to Backend Proxy 错误:无法代理请求(ECONNRESET)
【发布时间】:2020-03-14 01:36:12
【问题描述】:

问题:

我正在开发一个带有 Node Express 服务器和 MongoDB 的 React 应用程序。当尝试从客户端发帖或获取请求时,我们收到 500 状态码和以下错误:

Proxy error: Could not proxy request /api/workdays/allworkdays/5e5ee6a690f9a13de897d6a6 from localhost:3000 to http://localhost:3001/.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

在发布请求的情况下,信息会发布到数据库,但最终,我们确实会收到带有 500 状态代码的相同错误消息。

在获取请求的情况下,该请求在后端终端中得到控制台,但浏览器永远不会接收到。网络选项卡反映了(待定)指定,如下所示:

Screenshot of network tab from browser

get 请求的目的是查询我们的 Users 集合 - 检索所有链接的工作日 ID,然后查询 Workdays 集合并检索所有带有这些 ID 的文档。

错误消息提供了错误解释的链接 (ECONNRESET):

ECONNRESET (Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via the http and net modules.

我们希望将这个响应作为事件推送到状态。

我们应用的工作流程是 Component -> Axios Call -> API Routes -> Controller -> DB

任何有关此错误的帮助将特别感谢,因为我是一名希望很快被雇用的学生。除了学习之外,我正在做这个项目,目的是将它包含在我的投资组合中。

谢谢

我遇到的错误:

Screenshot of console error

我尝试过的事情:

React + Express: Proxy error: Could not proxy request /total from localhstem_errors

代码:

Package.json

{
  "name": "mern",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "proxy": "http://localhost:3001",
  "scripts": {
    "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
    "start:prod": "node server.js",
    "start:dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
    "client": "cd client && npm run start",
    "seed": "node scripts/seedDB.js",
    "install": "cd client && npm install",
    "build": "cd client && npm run build",
    "heroku-postbuild": "npm run build"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "concurrently": "^4.1.2",
    "nodemon": "^1.18.7"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "if-env": "^1.0.4",
    "is-empty": "^1.2.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.9.1",
    "passport": "^0.4.1",
    "passport-jwt": "^4.0.0",
    "react-big-calendar": "^0.24.0",
    "react-moment": "^0.9.7",
    "validator": "^12.2.0"
  }
}

组件

import React, { Component } from "react";
import moment from "moment";
import { connect } from "react-redux";
import { Calendar, momentLocalizer } from "react-big-calendar";
import "react-big-calendar/lib/css/react-big-calendar.css";
import Modal from "../Modal";

import workdaysAPI from "../../utils/workdaysAPI";
import { toast } from "react-toastify";

import "./calendar.css";

const localizer = momentLocalizer(moment);

class MyCalendar extends Component {
  componentDidMount() {
    workdaysAPI
      .getAllThisEmployeeWorkdays(this.props.auth.user.id)
      .then(dbModel => 
        this.setState({
          events: dbModel
        })
      )
      .catch(err => console.log(err));
  }

  constructor() {
    super();

    const events = [];, etc.

Axios 调用

**import axios from "axios";

export default {
  // Gets all workdays w/ user id
  getAllThisEmployeeWorkdays: function(id) {
    return axios.get("/api/workdays/allworkdays/" + id);
  }
};**

API 路由

const router = require("express").Router();
const workdaysController = require("../../controllers/workdaysController");

const Workday = require("../../models/Workday");

// Matches with "/api/workdays"
router
  .get("/allworkdays/:id", (req, res) => {
    workdaysController.findAllById
});

控制器

const db = require("../models");

// Defining methods for the workdaysController

module.exports = {
  findAllById: function(req, res) {
    db.User
      .findById({ _id: req.params.id })
      .populate("workday")
      .then(err, workday => {
        db.Workday
          .findById({ workday })
          console.log("Returning all workdays ", workday.workday);
          res.json(workday.workday) 
      })
      .catch(err => res.status(422).json(err));
  }, etc.

模型

用户

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  role: {
    type: String,
    required: true
  },
  workday: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'workdays'
  }],
  schedule: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'schedules'
  }]
});

module.exports = User = mongoose.model("users", UserSchema);

工作日

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const WorkdaySchema = new Schema({
  title: {
    type: String,
    required: true
  },
  availability: {
    type: Boolean,
    default: true
  },
  start: {
    type: Date,
    required: true
  },
  end: {
    type: Date,
    required: true
  },
  allDay: {
    type: Boolean,
    default: true
  }
});

module.exports = Workday = mongoose.model("workdays", WorkdaySchema);

【问题讨论】:

    标签: node.js reactjs mongodb


    【解决方案1】:

    所以,在查看代码 12986 次后,我发现下面的控制器文件的语法有错误:

    module.exports = {
      findAllById: function(req, res) {
        db.User
          .findById({ _id: req.params.id })
          .populate("workday")
          .then(err, workday => {
            db.Workday
              .findById({ workday })
              console.log("Returning all workdays ", workday.workday);
              res.json(workday.workday) 
          })
          .catch(err => res.status(422).json(err));
      }
    

    在您通过 id 查询数据库中的用户(并填充“工作日”字段)后,.then 不会抓取文档然后发送 json 响应(即res.json(document))。

    我建议您更改代码如下:

    findAllById: function(req, res) {
        db.User
          .findById(req.params.id)
          .populate("workday")
          .then(document => {
            res.json(document)
          console.log("Returning all workdays", document);
            return db.User.find(
              { workday: document }, 
            );
        })
      }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2020-12-13
      • 2018-05-18
      相关资源
      最近更新 更多