[英]Unable to send post request to MongoDB
我無法使用 fetch API/ Axio
將POST
請求從React js
客戶端發送到節點服務器(我都嘗試過)到MongoDB
.. 我遇到兩個問題。
我得到“ CastError: Cast to ObjectId failed for value \"add\" at path \"_id\" for model \"Contact\"" " 在我的服務器添加路由。
當我在前端提交我的反應表單時,在我的控制台上。
這是我的代碼 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;
我的 mongoose model
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;
第 2 點 - 錯誤請求:mongoose 拋出異常,因為您已將phone_number
的驗證設置為required:true
但您沒有給出它,這就是它進入.catch((err) => 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)
驗證您的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.