R
R
reinmaker902020-12-02 12:54:34
Node.js
reinmaker90, 2020-12-02 12:54:34

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);
  }
}

I receive it on the server and process it here:

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;
  }
});

Do I need to do additional checks at all with a post request? - something like this:

req.method === "POST"? /*делаем что-то*/ : /*обрабатываем ошибку*/

Is this generally necessary, or is the try-catch construct sufficient for all this in this case?
All this so that if the data received from the body of the request does not match the schema, throw an error, if everything is fine, send it to the database.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question