无法将发布请求发送到MongoDB

时间:2020-04-14 02:57:28

标签: javascript node.js reactjs mongodb express

我无法使用POSTReact js的{​​{1}}客户端(我已经尝试过)向节点服务器发送API/ Axio请求到节点服务器。我有两个问题。

  1. im收到“ CastError:在我的服务器添加路由中,模型\“ Contact \”“”路径\“ _ id \”的值\“ add \”的对象“ castError”的铸造失败li>

  2. 在我的控制台上,当我提交前端的我的反应表格时。

这是我的代码 Create.js-我的创建组件

MongoDB

Server.js

import React, { Component } from "react";
import axios from "axios";

export default class Create extends Component {
  constructor(props) {
    super(props);
    this.onFirstNameChange = this.onFirstNameChange.bind(this);
    this.onLastNameChange = this.onLastNameChange.bind(this);
    this.onNumberChange = this.onNumberChange.bind(this);
    this.onEmailChange = this.onEmailChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    this.state = {
      first_name: "",
      last_name: "",
      number: "",
      email: "",
      users: [],
    };
  }
  componentDidMount() {
    this.setState({
      users: ["test user"],
      first_name: "test",
      last_name: "test",
      number: "test",
      email: "test",
    });
  }
  onFirstNameChange(e) {
    this.setState({
      first_name: e.target.value,
    });
  }
  onLastNameChange(e) {
    this.setState({
      last_name: e.target.value,
    });
  }
  onNumberChange(e) {
    this.setState({
      number: e.target.value,
    });
  }
  onEmailChange(e) {
    this.setState({
      email: e.target.value,
    });
  }
  onSubmit(e) {
    e.preventDefault();
    const contact = {
      first_name: this.state.first_name,
      last_name: this.state.last_name,
      number: this.state.number,
      email: this.state.email,
    };
    console.log(contact);
    axios.post("http://localhost:8888/contacts/add", contact)
        .then(res => console.log(res.data));

    // fetch("http://localhost:8888/contacts/add", {
    //   method: "POST",
    //   headers: {
    //     'Accept': 'application/json',
    //     'Content-Type': 'application/json'
    //   },
    //   body: JSON.stringify(contact),
    // }).then((res) => console.log(res.data));
  }
  render() {
    return (
      <div>
        <h1>CREATE</h1>
        <form onSubmit={this.onSubmit}>
          <div className="first_name">
            <label htmlFor="">FIRST NAME</label>
            <input
              type="text"
              value={this.state.first_name}
              onChange={this.onFirstNameChange}
            />
          </div>
          <div className="last_name">
            <label htmlFor="">LAST NAME</label>
            <input
              type="text"
              value={this.state.last_name}
              onChange={this.onLastNameChange}
            />
          </div>
          <div className="number">
            <label htmlFor="">NUMBER</label>
            <input
              type="text"
              value={this.state.number}
              onChange={this.onNumberChange}
            />
          </div>
          <div className="email">
            <label htmlFor="">EMAIL</label>
            <input
              type="text"
              value={this.state.email}
              onChange={this.onEmailChange}
            />
          </div>
          <div className="submit">
            <input type="submit" value="Create Contact" />
          </div>
        </form>
      </div>
    );
  }
}

联系路线-

// Imports
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv").config();
// Server Variables
const server = express();

const url = "mongodb://localhost:27017";
const port = process.env.PORT || 8888;

server.use(cors({ origin: true, credentials: true }));
server.use(express.json({ extended: false }));

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
//Connecting to MongoDB
const uri = process.env.ATLAS_URI;
const dbConnection = mongoose.connection;
mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});
dbConnection.on("error", console.error.bind(console, "connection error:"));
dbConnection.once("open", () => {
  console.log("CONNECTED TO MONGO DB");
});

const usersRouter = require("./src/routes/users");
const contactRouter = require("./src/routes/contactRoutes");

server.use("/users", usersRouter);
server.use("/contacts", contactRouter);

server.listen(port, function () {
  console.log(`Server running on ${port}`);
});

我的猫鼬模型

const express = require("express");
const contactRouter = express.Router();
const Contact = require("../models/smart_contact_model");

// GETS ALL CONTACTS
contactRouter.route("/").get((req, res) => {
  Contact.find()
    .then((contacts) => res.json(contacts))
    .catch((err) => res.status(400).json("ERROR: " + err));
});
// ADDS SINGLE CONTACT TO DATABASE
contactRouter.route("/add").post((req, res) => {
  const first_name = req.body.first_name;
  const last_name = req.body.last_name;
  const number = req.body.number;
  const email = req.body.email;

  const newContact = new Contact({
    first_name,
    last_name,
    number,
    email,
  });

  newContact
    .save()
    .then(() => res.json("Contact Added."))
    .catch((err) => res.status(400).json("ERROR: " + err));
});
// FINDS SINGLE CONTACT
contactRouter.route("/:id").get((req, res) => {
  Contact.findById(req.params.id)
    .then((contacts) => res.json(contacts))
    .catch((err) => res.status(400).json("ERROR: " + err));
});
//
contactRouter.route("/:id").delete((req, res) => {
  Contact.findByIdAndDelete(req.params.id)
    .then(() => res.json(`Deleted ID: ${req.params.id}`))
    .catch((err) => res.status(400).json("ERROR: " + err));
});

contactRouter.route("/edit/:id").post((req, res) => {
  Contact.findByIdAndUpdate(req.params.id)
    .then((contact) => {
      contact.name = req.body.name;
      contact.number = req.body.number;

      contact
        .save()
        .then(() => res.json(`${req.params.id} has been updated.`))
        .catch((err) => res.status(400).json("ERROR: " + err));
    })
    .catch((err) => res.status(400).json("ERROR: " + err));
});

module.exports = contactRouter;

1 个答案:

答案 0 :(得分:0)

要点2-错误的请求:猫鼬抛出了异常,因为您已将phone_number的验证设置为required:true,但是您没有给出它,这就是它在{{ 1}}语句,您将使用http_code .catch((err) => res.status(400).json("ERROR: " + err))发送响应,这是BAD REQUEST的代码。
第1点-我的服务器中添加模型的路径“ Contact”的路径“ \ id_”的即时消息“ CastError:对值\ add>的CastId转换为ObjectId失败。:您是否收到此错误,我执行了代码,但没有找到此错误。但是,当您尝试制作ObjectId且未传递有效字符串(24个字符)时,就会出现此错误。您可以通过400来验证字符串