2016-10-01 137 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}));