Ask coding questions

← Back to all posts
How do you handle a post request in node.js using exress
Mathman05 (1)

How do you handle a post request in node.js using express?
I've tried and everything so far has failed. anyone know how?

Answered by EpicGamer007 (1736) [earned 5 cycles]
View Answer
Comments
hotnewtop
EpicGamer007 (1736)
// First, make sure you have a request parser.

app.use(express.json()); // To accept json post requests
app.use(express.urlencoded({ extended: true })); // to accept urlencoded requests

app.post("/post-endpoint", (req, res) => { // this is for the post

  console.log(req.body); // The post data will be here.
  res.send("Recieved request!")
  
});

Now here, i will expain what to do on the frontend

<!--One option is to use forms-->
<form action="/post-endpoint" method="post">
  <input type="text" name="input-example" placeholder="Enter some text!">
  <button type="submit">Send it</button>
</form>

The above code will be handled by the express.bodyparser and you will get a req.body with { "input-example": "the text you put in the textbox" }

It is also possible to send it with javascript.

fetch("/post-endpoint", {
  method: "POST",
  headers: {
    'Content-Type': 'application/json', // we will send a request with json
  },
  body: JSON.stringify({message: "Hello world!"})
}).then(res => console.log(res.body());

Hopefully this helps :)