Node.JS https请求返回JSON

时间:2017-03-03 10:11:17

标签: javascript json node.js https

我对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;
    }

我希望你能帮助我

1 个答案:

答案 0 :(得分:5)

要做你想做的事,你需要了解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();
  });
}




Here you can read more about asynchonous in javascript