Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Data Sent to NodeJS Server via Ajax Post

How do I access the data sent to a Nodejs Server via Ajax POST?

    //Client
$.ajax( {
    url: '/getExp',
    data: 'Idk Whats Rc',
    type: 'POST',
});

//Server
app.post('/getExp', function(req, res){
    var data = req.???; //I want data to be equal to 'Idk Whats Rc'
}
like image 915
RainingChain Avatar asked Sep 15 '13 04:09

RainingChain


1 Answers

Express 4.x:

Express 4 no longer contains Connect as a dependency, which means you will need to install the body parsing module separately.

The parser middleware can be found at its own GitHub repository here. It can be installed like so:

npm install body-parser

For form data, this is how the middleware would be used:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());

For Express 3.x and before:

You need to use the bodyParser() middleware in Express which parses the raw body of your HTTP request. The middleware then populates req.body.

app.use(express.bodyParser());
app.post('/path', function(req, res) {
  console.log(req.body);
});

You might want to pass an object instead of a string to your POST request because what you currently have will come out like this:

{ 'Idk Whats Rc': '' }

Using code somewhat like this:

$.ajax({
  url: '/getExp',
  data: { str: 'Idk Whats Rc' },
  type: 'POST',
});

Will get you this:

{ str: 'Idk Whats Rc' }
like image 117
hexacyanide Avatar answered Sep 18 '22 12:09

hexacyanide