#javascript #node.js #mongodb #mongoose
#javascript #node.js #mongodb #мангуст
Вопрос:
Прежде всего, я настоящий новичок в программировании, и я не могу понять, что с этим не так, он показывает только ошибку 404 not found
Ниже приведена моя схема mongoose
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema({
user_id: {
type: String,
required: true,
},
order_date: {
type: Date,
default: Date.now,
},
total_items: {
type: Number,
required: true,
},
total: {
type: Number,
required: true,
},
name: {
type: String,
},
address: {
type: String,
},
postalcode: {
type: String,
},
city: {
type: String,
},
country: {
type: String,
},
phonenumber: {
type: Number,
},
order_item_status: {
//purchased item delivery status, added by constant at saving from controller nmethod
type: String,
required: true,
},
quantity_array: [
{
type: String,
required: true,
},
],
purchase_array: [
{
type: String,
required: true,
},
],
item_array: [
{
type: String,
required: true,
},
],
});
module.exports = Order = mongoose.model("order", OrderSchema);
И ниже приведен набор данных, которые я отправляю.
{"user_id":"5f5058acc90b575a40d9e570",
"name":"Alfonso",
"address":"Victoria",
"postalcode":"11011B",
"city":"Moscow",
"country":"Russia",
"phonenumber":null,
"total_items":2,
"total":15,
"quantity_array":[2,1],
"purchase_array":["pb_single","pb_single"],
"item_array":["5f55e91271b808206c132d7c","5f55e8e171b808206c132d7a"]}
и ниже приведена функция, которую я использую для отправки вышеупомянутого объекта на сервер.
let orderComplete = {
user_id: localStorage.getItem("id"),
name: this.state.name,
address: this.state.address,
postalcode: this.state.postalcode,
city: this.state.city,
country: this.state.country,
phonenumber: this.state.phonenumber,
total_items: this.state.totalitems,
total: this.state.amount,
quantity_array: this.state.quantityArray,
purchase_array: this.state.purchaseTypeArray,
item_array: this.state.comicIdArray,
};
console.log("checkpoint : orderComplete" JSON.stringify(orderComplete));
var jwt_token = localStorage.getItem("currentToken"); //because it is a protected route
const config = {
headers: {
"Content-Type": "application/json",
"x-auth-token": jwt_token,
},
};
const body = JSON.stringify(orderComplete);
const result = await axios
.post("http://localhost:5000/createorder", body, config)
.then((res2) => {
console.log(res2);
toast.success(res2);
})
.catch((error) => {
toast.error(error);
console.log(error);
});
if (result == true) {
this.props.history.push("/products");
toast.success("Order Success");
}
}
И когда он перехватывается со стороны сервера
функция выглядит следующим образом
const createOrder = async (req, res) => {
try {
let user_id = req.body.user_id;
let purchase_type = req.body.purchase_type;
let item_array = req.body.item_array;
let quantity_array = req.body.quantity_array;
let purchase_array = req.body.purchase_array;
let total_items = req.body.total_items;
let total = req.body.total;
let name = req.body.name;
let address = req.body.address;
let postalcode = req.body.postalcode;
let city = req.body.city;
let country = req.body.country;
let phonenumber = req.body.phonenumber;
let order_item_status = "processing";
if (
purchase_type == false ||
user_id == false ||
item_array == false ||
quantity_array == false ||
purchase_array == false ||
total_items == false ||
total == false ||
name == false ||
address == false ||
postalcode == false ||
city == false ||
country == false ||
phonenumber == false
) {
return res.status(400).send("Not all mandatory values have been set!");
}
OrderObject = new Order({
//create object to set data
purchase_type,
user_id,
item_array,
quantity_array,
purchase_array,
total_items,
total,
name,
address,
postalcode,
city,
country,
phonenumber,
order_item_status,
});
await OrderObject.save();
res.status(200).send("Order success");
} catch (error) {
console.log("Error caught at ", error);
res.status(500).send("Server Error");
}
};
Я пытался снова и снова, но я не могу понять, что с этим не так, даже обработчики исключений не содержат много информации.
пожалуйста, мне отчаянно нужна ваша помощь, спасибо.
Комментарии:
1. 404 — это ошибка с кодом состояния страницы, не найденной. Предполагая, что ваш API хорошо построен, вы проверили конечную точку, к которой пытаетесь подключиться? попробуйте отправить эти данные
http://localhost:5000/createorder
в postman и фактически подтвердите в серверной части, что конечная точка существует2. Добавили ли вы какие-либо серверные маршруты для обработки запроса?
3. @myrdstom вы только что спасли мой день, это было то, что я забыл упомянуть серверный маршрутизатор для app.js . Большое вам спасибо, ребята
4. Потрясающе 🙂 рад, что вы это поняли