2013-02-23 68 views
6

我正在嘗試獲取我在節點應用程序中發送的ajax帖子的值。使用this post爲指導,我有這個至今:閱讀Node.JS中的AJAX post變量(使用Express)

在節點:

var express = require('express'); 
var app = express(); 

var db = require('./db'); 

app.get('/sender', function(req, res) { 
    res.sendfile('public/send.html'); 
}); 

app.post('/send_save', function(req, res) { 
    console.log(req.body.id) 
    console.log(req.body.title); 
    console.log(req.body.content); 
    res.contentType('json'); 
    res.send({ some: JSON.stringify({response:'json'}) }); 
}); 

app.listen(3000); 

上的AJAX一面:

$('#submit').click(function() { 
      alert('clicked') 
      console.log($('#guid').val()) 
      console.log($('#page_title').val()) 
      console.log($('#page-content').val()) 
      $.ajax({ 
       url: "/send_save", 
       type: "POST", 
       dataType: "json", 
       data: { 
        id: $('#guid').val(), 
        title: $('#page_title').val(), 
        content: $('#page-content').val() 
       }, 
       contentType: "application/json", 
       cache: false, 
       timeout: 5000, 
       complete: function() { 
        //called when complete 
        console.log('process complete'); 
       }, 

       success: function(data) { 
        console.log(data); 
        console.log('process sucess'); 
       }, 

       error: function() { 
        console.log('process error'); 
       }, 
       }); 
     }) 

這個問題,我不能req.body .id(以及任何其他值,如標題或內容),我得到節點中的此錯誤:

TypeError: Cannot read property 'id' of undefined 

如果我評論thos e電話雖然,阿賈克斯是成功的。我搞不清楚了。我忘記了什麼嗎?

+0

我有同樣的問題 - 嘗試使用'PARAM ('postVariableName')' – fider 2014-01-08 23:58:22

回答

7

req您在那裏擁有的對象沒有body屬性。看看http://expressjs.com/api.html#req.body

此屬性是一個對象,其中包含解析的請求正文。這個 功能由bodyParser()中間件提供,但解析中間件的其他主體 也可能遵循此約定。當使用bodyParser()時,此屬性 默認爲{}。

所以,你需要將bodyParser中間件添加到您的快遞web應用是這樣的:

var app = express(); 
app.use(express.bodyParser()); 
+0

啊,我知道我錯過了一些重要的東西!但是,當我包括這個時,我開始收到'壞請求:錯誤請求'的迴應。這有什麼關係?我必須通過npm安裝嗎? – streetlight 2013-02-23 15:48:40

+0

@streetlight:我不認爲你必須安裝任何東西,但我不知道是什麼原因導致了這個錯誤。 – thejh 2013-02-23 15:53:36

+0

啊,好吧,謝謝你的幫助!這個應用幾乎沒有什麼,所以我不知道這個不好的請求發生了什麼事情! – streetlight 2013-02-23 15:58:47

6

問題確實是由包括bodyParser中間件通過thejh所建議的解決。

只要確保參觀了這個問題的答案提供的網址訪問快速更新的規範:http://expressjs.com/api.html#req.body

的文檔提供了這個例子(快遞4.x版):

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

app.use(bodyParser.json()); // for parsing application/json 
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded 
app.use(multer()); // for parsing multipart/form-data 

app.post('/', function (req, res) { 
    console.log(req.body); 
    res.json(req.body); 
}) 

這個工作身體解析器模塊需要單獨安裝:

https://www.npmjs.com/package/body-parser