hundred_dolla_tea hundred_dolla_tea - 6 months ago 30
iOS Question

Request body in express is undefined?

I am making a simple POST request using Alamofire (in iOS) and handling it in node using express.
My code in iOS:

let boop: [String: AnyObject] = ["username":"fakeuser"];
Alamofire.request(.POST,"http://localhost:3000/test", parameters: boop, encoding: .JSON)


And this is my code in node:

var app = require('express')();
var http = require('http').Server(app);
app.post('/test', function(req, res){
console.log("THE SERVER HAS RECEIVED THE POST! \n")
console.log(req.body);
});

http.listen(PORT, function(){
console.log('listening on *:3000');
});


My terminal console prints out "the server has received the post" , so I know that the post is actually triggered. The issue is that instead of logging the req.body, it instead prints out "undefined". I've looked around and it seems like a "body parser" thing needs to be configured but apparently that is obsolete with the new version of express. So I am lost as to what to do.

Any advice?

Answer

I'm pretty sure you need to add the body-parser to your express app to parse the JSON.

const bodyParser = require('body-parser');
app.use(bodyParser.json());

See http://expressjs.com/de/api.html#req.body.