2015-11-19 135 views
3

我在NodeJs上做了一個小型項目。 其實我有一個系統,用戶按下某個按鈕,當按下按鈕時,在用戶界面上執行某個動作(即:在HTML中修改)。除此之外,我還想將用戶歷史保存在數據庫中。與用戶按下哪個命令或按鈕一樣。 如何在客戶端的Nodejs中執行此操作,因爲我無法在客戶端使用require(「http」)函數。 我正在使用mogoodb(Modulus在線數據庫)來保存數據。我已經寫了一個發佈請求(在服務器端)來保存數據,這非常完美。使用腳本發送http post並從客戶端獲取NODEJS請求

var Record = require('../app/models/record'); 
app.post('/saveuserhistory', function(req, res, next) { 

    var newRecord   = new Record(); 
    newRecord.email = req.loggedinUser; 
    newRecord.commands = "test_command"; 
    newRecord.sampledata1 = "sample1"; 
    newRecord.sampledata2 = "sample2";  
    Record.create(newRecord, function (err, post) { 
    if (err){ 
     return next(err) 
    } 
    else{ 
     res.json(post); 
    } 
    }); 
}); 
+2

您可以從編寫一些代碼開始,通常可以幫助 –

+0

如何使用腳本從客戶端調用: localhost:8080/saveuserhistory 。 – Umer

回答

1
var x = new XMLHttpRequest(); 

    x.onreadystatechange = function(){ 
    if(x.status === 200 && x.readyState === 4) { 
     // Optional callback for when request completes 
     console.log(x.responseText); 
    } 
    } 

    x.open('POST', '/saveuserhistory', true); 
    x.send('email=' + someUserEmail + '&someData=' + someData); 

這發出一個POST請求到當前URL的/saveuserhistory端點,與一對夫婦的數據塊。我建議使用jQuery的$.ajax()方法或Angular的$http以獲得更清晰的語法和更多的跨瀏覽器功能。

相關問題