【问题标题】:Unable to send post request to MongoDB无法向 MongoDB 发送 post 请求
【发布时间】:2020-04-14 02:57:28
【问题描述】:

我无法使用 fetch API/ Axios(我都尝试过)将 POST 请求从 React js 客户端发送到节点服务器到 MongoDB .. 我有两个问题。

  1. 我在我的服务器添加路由中收到“ CastError: Cast to ObjectId failed for value \"add\" at path \"_id\" for model \"Contact\"" "”。

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

这是我的代码 Create.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>
    );
  }
}

服务器.js

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

我的猫鼬模型

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const contactSchema = new Schema(
  {
    first_name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    last_name: {
      type: String,
      required: true,
      unique: true,
      trim: true,
    },
    phone_number: {
      type: Number,
      required: true,
      trim: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      trim: true,
      unique: true,
    },
    gender: {
      type: String,
      required: false,
      trim: true,
      unique: false,
    },
    instagram: {
      type: String,
      required: false,
      trim: true,
      unique: true,
    },
    twitter: {
      type: String,
      required: false,
      trim: true,
      unique: true,
    },
    snapchat: {
      type: String,
      required: false,
      trim: true,
      unique: true,
    },
    intimacy: [Number],
    interest: [String],
    industry: {
      type: String,
    },
    job: {
      type: String,
    },
  },
  {
    timestamps: true,
  }
);

const contactModel = mongoose.model("Contact", contactSchema);
module.exports = contactModel;

【问题讨论】:

    标签: javascript node.js reactjs mongodb express


    【解决方案1】:

    第 2 点 - 错误请求:mongoose 抛出异常,因为您已将 phone_number 的验证设置为 required:true,但您没有给出它,这就是它出现在 .catch((err) =&gt; res.status(400).json("ERROR: " + err)) 语句中的原因您正在发送带有 http_code 400 的响应,这是 BAD REQUEST 的代码。
    第 1 点 - 我收到“ CastError: Cast to ObjectId failed for value \"add\" at path \"_id\" for model \"Contact\"" " 在我的服务器中添加路由。:您在哪里收到此错误,我执行了您的代码,但没有发现此错误。但是当您尝试创建 ObjectId 并执行未传递有效字符串(24 个字符)。您可以通过 mongoose.Types.ObjectId.isValid(YOUR_STRING) 验证您的字符串

    【讨论】:

      猜你喜欢
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2014-08-04
      • 1970-01-01
      相关资源
      最近更新 更多