Human Cyborg Relations Human Cyborg Relations - 2 months ago 8
Ajax Question

Ajax POST request sending undefined to Express

I'm trying to send some data to be parsed. The script on the client side is the following:

function addURL(link) {
console.log("Adding url...");
$.ajax({
type: "POST",
url: location.protocol + "//" + location.host + "/shorturl/create",
crossDomain: true,
contentType: "application/json",
data: JSON.stringify({url:link}),
success: function(data){
$("#shortenedURL").html(data.shortenedURL);
},
error: function(err){
console.log("Ran into an error... " + err);
}
});
}


On my express app, on one of the routers, I've got:

router.post("/create", function(req, res){

console.log(req.body);
console.log(req.body.url);
var url = req.body.url; }


I get 'undefined', and then the 'Cannot get property 'url' of undefined'.

I can't figure out where I'm going wrong...

Answer

You need to use bodyParser:

app.js:

var bodyParser = require('body-parser')
  , app = express();

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