2016-10-12 51 views
0

編輯請參閱下面爲該修復程序接受的答案。我還必須從我的POST請求中刪除行contentType: 'appliction/json',在Express中接收Jquery POST數據

我想向Node.js/Express發送一個字符串,但req.body是未定義的服務器端。

客戶端的jQuery:

$.post({ 
     traditional: true, 
     url: '/matches', 
     contentType: 'appliction/json', 
     data: viewedProfiles, 
     dataType: 'json', 
     success: function(response){ 

快遞:

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

app.post('/matches', isLoggedIn, function(req, res){ 
    console.log(req.body) // this is undefined 
    var loadedProfiles = [] 
    loadedProfiles.push(req.body.viewedProfiles) 
    console.log('loadedProfiles') 
    console.log(loadedProfiles) 

我已經試過:

  • 不指定 '的dataType'
  • 設置data: JSON.stringify(viewProfiles)
  • 分割字符串到一個數組在客戶端上,然後將具有jQuery的字符串化它
  • 尋找req.params代替req.body(在吸管抓着)

我可以看到在開發工具的XHR請求,它包含我期待的字符串。

我錯過了什麼超級明顯的東西發送數據到Express?

謝謝。

+0

你有'連接在你的頁面中運行的中間件? –

+0

我沒有,但我有jQuery數據職位在應用程序的其他地方成功運行。 –

回答

1

您的服務器端代碼看起來不錯,但您需要使用$.ajax()而不是$.post()函數,因爲$.post()函數會將數據發送到url(使用url編碼)。所以,你的jQuery代碼會

$.ajax({ 
     url: '/matches', 
     type: 'POST', 
     contentType: 'application/json', 
     data: JSON.stringify({"viewedProfiles": viewedProfiles}), 
     success: function(response){ 

我希望這將有助於你

+0

是的,這真的幫助了我!在它工作之前,我還必須刪除'contentType:'appliction/json''行。 –

0

我已配置完全相同的設置。而下面的代碼工作:

var profiles = { 'data' : 'hello' }; 

$.post({ 
     traditional: true, 
     url: '/matches', 
     contentType: 'application/json', 
     data: JSON.stringify(profiles), 
     dataType: 'json', 
     success: function(response){ console.log(response); } 
}); 

我的NodeJS引擎:

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

app.post('/matches' , function(req, res){ 
    console.log(req.body) // this outputs: { data: 'hello' } 
}); 

順便說一句,有一個錯字在您的contentType是, '應用程一個重刑/ JSON'