2017-05-15 22 views
0

我已經休息呼叫,在那裏它需要一個參數EMPID傳遞類型如何消耗POST調用,其中參數是類型的應用/ X WWW的窗體-urlencoded在節點JS

application/x-www-form-urlencoded 

enter image description here

蔭試圖消耗,使用以下code.But值越來越爲未定義傳遞給restcall

function searchEmployee(employeeid){ 
     var empEndpoint = 'http://localhost:3001/searchemp'; 
     var http = new XMLHttpRequest(); 
     http.open('POST',empEndpoint,true); 
     http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
     var empid = employeeid; 
     http.send(empid) ; 
    } 

請能有人指出錯誤,並幫助我如何以正確的格式發佈。

***編輯添加的服務器代碼

app.post('/searchemp',function(req,res){ 
    reqbody = req.body.empid; 
    console.log(reqbody,"reqbody"); 
    var empdetails =con.query('SELECT * FROM tasktable WHERE Empid =?',reqbody, 
    function(err,rows){ 
     if(err) throw err; 

     console.log('EMP Data received from Db:\n'); 
     res.send(rows); 
}); 
}); 
+0

https://www.npmjs.com/package/ body-parser你需要添加它來解析正文數據。希望這可以幫助。 –

回答

0

這取決於你來自哪裏調用函數searchEmployee,你是怎麼做的。

作爲var empid = employeeid;employeeid是你的函數的第一個參數,你應該調用searchEmployee與適當的參數,如2474

所以你應該把它像:

searchEmployee(2474); 
 

 
function searchEmployee(employeeid){ 
 
     var empEndpoint = 'http://localhost:3001/searchemp'; 
 
     var http = new XMLHttpRequest(); 
 
     http.open('POST',empEndpoint,true); 
 
     http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 
 
     var params = `empid=${empid}`; 
 
     http.send(params);    
 
    }

也許這會有所幫助:http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

var url = "get_data.php"; 
 
var params = "lorem=ipsum&name=binny"; 
 
http.open("POST", url, true); 
 

 
//Send the proper header information along with the request 
 
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
 
http.setRequestHeader("Content-length", params.length); 
 
http.setRequestHeader("Connection", "close"); 
 

 
http.onreadystatechange = function() {//Call a function when the state changes. 
 
\t if(http.readyState == 4 && http.status == 200) { 
 
\t \t alert(http.responseText); 
 
\t } 
 
} 
 
http.send(params);

尤其是這應該是要走的路:

var params = "lorem=ipsum&name=binny";

您的等效應該是這樣的:

var params = `empid=${empid}`; 
 
http.send(params);

+0

@ driedel.Yes Iam正在做同樣的事情。但是empid到達了未定義的節點js restcall – user7350714

+0

您的服務器端代碼的外觀如何? – driedel

+0

也許這有助於: – driedel

相關問題