-1

I create node.js server and parse jquery request.

jquery request:

 $.post("http://localhost:3000/usertoken/",
        {
          "token": "1212555",
        },
        function(data,status){


 alert("Data: " + data + "\nStatus: " + status);
        }); 

Node server

var express = require('express');
var sub_server = require('./sub_server.js'); 
var bodyParser = require('body-parser')

var app = express();
app.listen(3000);
app.use(express.static('www'))
// parse application/json
app.use(bodyParser.json())


app.get('/:id', function(req, res){
    console.log("request:",req.params.id);
    res.send('The id you specified is ' + req.params.id);
});

var firebase_token;
// Post method
app.post('/usertoken', function(req, res){

    var token1 = req.body.token;;
    console.log("req parameter:",token1);

    res.end( JSON.stringify("hemant"));

});

I am getting below message. req parameter: undefined

Help me to get post value.

Thank you.

2 Answers2

0

Make sure you use body-parser:

var bodyParser = require('body-parser');

And use:

app.use(bodyParser.json());

if you use JSON body in requests, or this:

app.use(bodyParser.urlencoded({ extended: false }));

if you use application/x-www-form-urlencoded - in both cases make sure you send the right MIME type in the request.

See the docs: https://www.npmjs.com/package/body-parser

For more info see these answers:

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
0

While your server should work correctly, your client does not.

You are missing the contentType option on the $.post call. As you can only specify this parameter if you hand over everything within an object, change the call to the following code to make sure that you not only send JSON data, but that you also set the content-type header accordingly:

$.post({
  url: "http://localhost:3000/usertoken/",
  data: {
    "token": "1212555",
  },
  contentType: "application/json",
  success: function (data, status) {
    // ...
  }
});

The body-parser middleware only becomes active if the content-type header points out that you are sending JSON data.

Golo Roden
  • 140,679
  • 96
  • 298
  • 425