[英]Node.JS https request return JSON
我對Node.js HTTPS請求有疑問。 該請求將發送到服務器,該服務器將返回JSON響應。 然后,我想解析響應並將其存儲在變量中,並與其他函數一起使用。
let obj=JSON.parse(response);
return obj;
我寫的功能:
let protocol="https";
let hostStr="www.example.com";
let pathStr="***";
let students=makeRequest("ABCDEFG","getStudents"));
console.log(students);
function makeRequest(token,method){
let obj='';
let options={
host:hostStr,
path:pathStr,
method:"POST",
headers:{"Cookie":"JSESSIONID="+token}
};
let https=require(protocol);
callback = function(response){
var str='';
response.on('data',function(chunk){
str+=chunk;
});
response.on('end',function(){
obj=JSON.parse(str);
});
}
let request=https.request(options,callback);
request.write('{"id":"ID","method":"'+method+'","params":{},"jsonrpc":"2.0"}');
request.end();
return obj;
}
我希望你能幫幫我
要執行您想要的操作,您需要了解Javascript的異步方面。 您不能執行任何操作,因為字符串是在異步回調中更新的。 我已修復了無效的部分。
let protocol="https"; let hostStr="www.example.com"; let pathStr="***"; makeRequest("ABCDEFG","getStudents")) .then(students => { // here is what you want console.log(students); }); function makeRequest(token,method){ return new Promise(resolve => { let obj=''; let options={ host:hostStr, path:pathStr, method:"POST", headers:{"Cookie":"JSESSIONID="+token} }; let https=require(protocol); callback = function(response){ var str=''; response.on('data',function(chunk){ str+=chunk; }); response.on('end',function(){ obj=JSON.parse(str); resolve(obj); }); } let request = https.request(options,callback); request.write('{"id":"ID","method":"'+ method +'","params":{},"jsonrpc":"2.0"}'); request.end(); }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.