How to receive JSON in express node.js POST request?

前端 未结 2 661
心在旅途
心在旅途 2020-12-14 09:03

I send a POST WebRequest from C# along with a JSON object data and want to receive it in a Node.js server like this:

var express = require(\'exp         


        
相关标签:
2条回答
  • 2020-12-14 09:29

    The request has to be sent with: content-type: "application/json; charset=utf-8"

    Otherwise the bodyParser kicks your object as a key in another object :)

    0 讨论(0)
  • 2020-12-14 09:42

    bodyParser does that automatically for you, just do console.log(req.body)

    Edit: Your code is wrong because you first include app.router(), before the bodyParser and everything else. That's bad. You shouldn't even include app.router(), Express does that automatically for you. Here's how you code should look like:

    var express = require('express');
    var app = express.createServer();
    
    app.configure(function(){
      app.use(express.bodyParser());
    });
    
    app.post('/ReceiveJSON', function(req, res){
      console.log(req.body);
      res.send("ok");
    });
    
    app.listen(3000);
    console.log('listening to http://localhost:3000');
    

    You can test this using Mikeal's nice Request module, by sending a POST request with those params:

    var request = require('request');
    request.post({
      url: 'http://localhost:3000/ReceiveJSON',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        a: 1,
        b: 2,
        c: 3
      })
    }, function(error, response, body){
      console.log(body);
    });
    

    Update: use body-parser for express 4+.

    0 讨论(0)
提交回复
热议问题