Ken
Ken

Reputation: 59

node.js express.js post data

I encountered a problem in getting client POST data as follow:

my client sent:

content-type:application/x-www-form-urlencoded

the content:

{"value":"123456"}

In node.js, it is no problem to parse the content to a json object, my code as follow:

http.createServer(function onRequest(request, response) {               
    request.setEncoding("utf8");
    var content = [];

    request.addListener("data", function(data) {
        content.push(data); //Collect the incoming data});

    //At the end of request call
    request.addListener("end", function() {
    response.writeHead( 200, {"Content-Type": "text/plain"} );
    ms = content[0];
    if(ms.toString() != "")
    {
        var msg = ms.toString();    //Parse the ms into string      
        console.log(msg); // Prints the message in the console
        var reqObj = JSON.parse(msg);   // If the incoming message is in JSON format, it can be parsed as JSON.
        console.log(reqObj); 
        response.end(); //Close the response
    }
});

Output of the above code: {"account": "48264"} //before parse to JSON { account: '48264' } //after parse to JSON

but when I changed into express.js and use bodyParser, it mixed up.

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.post('/', function(req, res, next) {
    req.setEncoding('utf8');
    console.log(req.body);
    console.log(req.body.value);
});
module.exports = router;

The above outputs in the console as follow:

{ "{\"account\": \"123456\"}": "" }
undefined

I searched the web, but can't find the solution. please help. Thanks in advance

Upvotes: 0

Views: 1421

Answers (1)

Kunal Kapadia
Kunal Kapadia

Reputation: 3353

You need to use express body-parser middleware before defining any routes.

var bodyParser = require('body-parser');
var app = express();
port = parseInt(process.env.PORT, 10) || 8080;

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse application/json
app.use(bodyParser.json());

app.listen(port);

app.post("/someRoute", function(req, res) {
  console.log(req.body);
  res.status(200).json({ status: 'SUCCESS' });
});

Upvotes: 2

Related Questions