2016-10-01 128 views
1

我想发送一些数据进行解析。在客户端脚本如下:Ajax POST请求发送undefined到Express

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'。

我想不通我要去哪里错了...

+0

你确定的网址:你发送的链接对ajax有价值吗? –

+0

你正在使用什么expressjs版本,并发布你的app.js代码 –

回答

2

您需要使用bodyParser

app.js:

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

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