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...
You need to use bodyParser :
app.js:
var bodyParser = require('body-parser')
, app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.