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'
}
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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With