How can I read the data received in application/x-www-form-urlencoded format on Node server?

If you are using Express.js v4.16+ as Node.js web application framework:

import express from "express";

app.use(bodyParser.json()); // support json encoded bodies
app.use(express.urlencoded({ extended: true })); // support encoded bodies

// With body-parser configured, now create our route. We can grab POST 
// parameters using req.body.variable_name

// POST http://localhost:8080/api/books
// parameters sent with 
app.post('/api/books', function(req, res) {
  var book_id = req.body.id;
  var bookName = req.body.token;
  //Send the response back
  res.send(book_id + ' ' + bookName);
});

For versions of Express.js older than v4.16 you should use the body-parser package:

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// With body-parser configured, now create our route. We can grab POST 
// parameters using req.body.variable_name

// POST http://localhost:8080/api/books
// parameters sent with 
app.post('/api/books', function(req, res) {
  var book_id = req.body.id;
  var bookName = req.body.token;
  // Send the response back
  res.send(book_id + ' ' + bookName);
});

Leave a Comment