React / Express App-API请求后端代理错误:无法代理请求(ECONNRESET)

时间:2020-03-14 01:36:12

标签: node.js reactjs mongodb

问题:

我正在使用带有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状态代码的错误消息。

对于get请求,该请求在后端终端中进行控制,但浏览器从不接收。网络标签反映了一个(待定)名称,例如:

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);

1 个答案:

答案 0 :(得分:0)

因此,在检查了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向数据库查询User(并填充了“工作日”字段)之后,.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 }, 
        );
    })
  }

希望这会有所帮助!