Search code examples
node.jshttp-post

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


I'm receiving data on a webhook URL as a POST request. Note that the content type of this request is application/x-www-form-urlencoded.

It's a server-to-server request. And On my Node server, I simply tried to read the received data by using req.body.parameters but resulting values are "undefined"?

So how can I read the data request data? Do I need to parse the data? Do I need to install any npm module? Can you write a code snippet explaining the case?


Solution

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