Answer the question
In order to leave comments, you need to log in
How to handle POST request in Node?
The client knocks on the server and gives it the object:
async function postData() {
try {
let res = await fetch("http://localhost:3000/data", {
method: "POST",
mode: "cors",
body: JSON.stringify({
name: "Vasya",
age: 10,
status: true,
}),
headers: { "Content-type": "application/json" },
});
console.log(res);
let data = await res.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
app.post("/data", async (request, response) => {
try {
let user = new Data({
name: request.body.name,
age: request.body.age,
status: request.body.status,
});
await user.save();
response.redirect("/main-page");
} catch (error) {
throw error;
}
});
req.method === "POST"? /*делаем что-то*/ : /*обрабатываем ошибку*/
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question