2016-03-04 122 views
0

有沒有辦法讓ajax發佈一個對象數組,然後在node.js服務器上解析它?這裏是我的客戶端代碼:如何將AJAX POST對象數組發佈到node.js服務器?

var context = []; 

obj1 = { 
     first_name: 'e', 
     last_name: 'e', 
     contact_email: 'e', 
     contact_phone_num: 'e', 
     contact_notes: 'e' 
    } 


    obj2 = { 
     first_name: 'a', 
     last_name: 'a', 
     contact_email: 'a', 
     contact_phone_num: 'a', 
     contact_notes: 'a' 
    } 


    var context = []; 

    context.push(obj1); 
    context.push(obj2) 


    $.ajax({ 
    type: "POST", 
    url: '/api/addcontact', 
    data: context, 
    success: function(data, status) { 
     alert('company added!'); 

    }, 
    error: function(data, status, res) { 
     console.log('err: ' + res); 
    } 
}); 

我的服務器端代碼:

api.post('/api/addcompany', function(req, res) { 
    console.log('add company hit'); 
    console.log(req.body); //returns {} 
    res.sendStatus(200); 
}); 

現在,當我打印返回{}請求主體。

有人可以幫助我在服務器端正確訪問對象數組嗎?

在此先感謝!

+0

您正在使用哪一個身體分析中間件? – mscdex

回答

0

發生這種情況是因爲您沒有在您的ajax帖子內發送對象,而是發送了一個數組。嘗試在{}中包裝數組來表示它確實是一個對象,然後在您的服務器代碼中引用該對象屬性。

var context = []; // array 

    context.push(obj1); 
    context.push(obj2) 


    $.ajax({ 
    type: "POST", 
    url: '/api/addcontact', 
    data: {context: context}, // requires an object here 
    success: function(data, status) { 
     alert('company added!'); 

    }, 
    error: function(data, status, res) { 
     console.log('err: ' + res); 
    } 
}); 

然後在您的服務器端腳本中,您可以引用正文對象的context屬性。

0

首先,您應該刪除context變量之一。當你宣佈它已經在頂端時,就不需要第二個了。

其次,它似乎是你張貼到錯誤的網址,應該是/api/addcompany/api/addcontact

相關問題