Ajax POST请求发送undefined到Express
我试图发送一些数据来parsing。 客户端的脚本如下:
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); } }); }
在我的快递应用上,在其中一台路由器上,我有:
router.post("/create", function(req, res){ console.log(req.body); console.log(req.body.url); var url = req.body.url; }
我得到“未定义”,然后“无法获取属性”URL“未定义”。
我不知道我要去哪里错了…
你需要使用bodyParser :
app.js:
var bodyParser = require('body-parser') , app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true}));