Apa*_*tus 0 javascript https json node.js
我有关于Node.js HTTPS请求的问题.请求转到服务器,该服务器将返回JSON响应.然后我想解析响应并将其存储在变量中并与其他函数一起使用.
let obj=JSON.parse(response);
return obj;
Run Code Online (Sandbox Code Playgroud)
我写的功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望你能帮帮我
要做你想做的事,你需要了解Javascript的asynchrone方面.你做的事情无法工作,因为字符串是在异步回调中更新的.我修复了无效的部分.
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();
});
}Run Code Online (Sandbox Code Playgroud)
在这里,您可以在javascript中阅读更多关于asynchonous的内容