2012-07-26 74 views
1

在客戶端,我使用jQuery數據發佈數據:Node.js的表達:無法獲取的jQuery AJAX發佈

 var data = { 
      'city': 'england' 
     } 
     $.ajax({ 
      'type': 'post', 
      'url': 'http://127.0.0.1:8000/', 
      'data': data, 
      'dataType': 'json', 
      'success': function() { 
       console.log('success'); 
      } 
     }) 

在我server.js,我試圖抓住後的數據:

var express = require('express'); 
var app = express.createServer(); 
app.configure(function() { 
    app.use(express.static(__dirname + '/static')); 
    app.use(express.bodyParser()); 
}) 

app.get('/', function(req, res){ 
    res.send('Hello World'); 
}); 

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

後能成功,它返回200個狀態,但我無法登錄後的數據,它返回任何結果,並且終端日誌undefined

爲什麼?我怎麼解決這個問題?

回答

2

您沒有發送正確的數據。

$.ajax({ 
    type: 'POST', 
    data: JSON.stringify(data), 
    contentType: 'application/json', 
    url: '/endpoint' 
}); 

使用jQuery,使用

的contentType: '應用/ JSON'

發送JSON數據。

+0

不,它仍然不起作用,contentType已經改變爲json.But發佈的數據仍然不能顯示 – hh54188 2012-07-26 15:29:51

+0

你使用的是什麼版本的express?我在2.5.8 – Rajat 2012-07-26 17:58:05