代理错误:无法将请求/用户/更新从localhost:3000代理到http:// localhost:5000

时间:2020-07-31 05:29:49

标签: node.js reactjs

所以我有一个MERN应用程序,并且一切正常。发布,获取和删除所有工作正常,但是在我的React终端上,我不断收到错误消息

Proxy error: Could not proxy request /user/update from localhost:3000 to 
http://localhost:5000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information. 
(ECONNRESET).

我只是失去了我的应用程序如何正常工作,喜欢它添加,删除,并从我的MongoDB服务器获取数据不错,但此消息不断弹出。我已经对路线进行了一些更改,以尝试使其在heroku上运行,但效果也不理想。但是在本地,除了我不断收到的错误消息外,其他一切似乎都可以正常工作。

在我指定的package.json中

"proxy": "http://localhost:5000/"

我的server.js是

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");

// Allow to get information from .env file
require("dotenv").config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const url = process.env.ATLAS_URL;

// Express.static --> charge of sending static files requests to the client
app.use(express.static(path.join(__dirname, "client", "public")));

mongoose.connect(url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
});

// Checking to see if mongoose connection was successful
const connection = mongoose.connection;
connection.once("open", () => {
  console.log("MongoDB database connection established successfully");
});

// Routes
const userRouter = require("./routes/user");

app.use("/user", userRouter);

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/public"));
}

// "Catchall" route hander.
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "client", "public", "index.html"));
});

app.listen(port, () => {
  console.log("Server is running on port: " + port);
});

我的路线是这个

const router = require("express").Router();
const User = require("../models/user.model");

// Gets users from database
router.route("/").get((req, res) => {
  User.find()
    .then((user) => res.json(user))
    .catch((err) => res.status(400).json("Error: " + err));
});

// Adds a new user to the userDB
router.route("/signup").post((req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const email = req.body.email;

  const newUser = new User({
    username,
    password,
    email,
  });

  newUser
    .save()
    .then(() => res.json("User added to userDB"))
    .catch((err) => res.status(400).json("Error: " + err));
});

// Adds a new todoList for the current user
router.route("/update").post((req, res) => {
  const userId = req.body.id;

  const newTodoList = {
    title: req.body.title,
    content: req.body.content,
  };

  // Finds user and updates the todoList for that user
  const filter = { _id: userId };
  const update = { $push: { todoList: newTodoList } };
  User.findOneAndUpdate(filter, update)
    .then(() => res.json("User updated with todoList"))
    .catch((err) => res.status(400).json("Error: " + err));
});

// Gets userId and noteId from parameters and find the current user and deletes the note that wants to be deleted.
router.route("/delete/:userId/:noteId").delete((req, res) => {
  const userId = req.params.userId;
  const noteId = req.params.noteId;

  const filter = { _id: userId };
  const update = { $pull: { todoList: { _id: noteId } } };

  User.findOneAndUpdate(filter, update)
    .then(() => res.json("Note Deleted"))
    .catch((err) => res.status(400).json("Error: " + err));
});

module.exports = router;

我的React客户端代码如下

import React, { useState } from "react";
import axios from "axios";
import AddIcon from "@material-ui/icons/Add";

function CreateArea(props) {
  const [isExpanded, setIsExpanded] = useState(false);

  const [note, setNote] = useState({
    id: "",
    title: "",
    content: "",
  });

  // Updating hooks when user types
  function handleChange(e) {
    const { name, value } = e.target;
    setNote((prevNote) => {
      return {
        ...prevNote,
        [name]: value,
        id: props.id,
      };
    });
  }

  // Posting note to db
  function submitNote(e) {
    // Clears user's title and content after user clicks submit button
    setNote({
      id: "",
      title: "",
      content: "",
    });
    // Posts user with new todoList
    axios.post("/user/update", note).then((res) => console.log(res.data));
  }

  function expand() {
    setIsExpanded(true);
  }

  return (
    <div>
      <form className="createArea">
        {isExpanded ? (
          <input
            name="title"
            onChange={handleChange}
            value={note.title}
            placeholder="Title"
          />
        ) : null}
        <textarea
          name="content"
          onChange={handleChange}
          value={note.content}
          placeholder="Take a note..."
          rows="3"
          onClick={expand}
        />
        {isExpanded ? (
          <button onClick={submitNote}>
            <AddIcon />
          </button>
        ) : null}
      </form>
    </div>
  );
}

export default CreateArea;

0 个答案:

没有答案