简体   繁体   中英

Node.JS https request return JSON

I have a question about the Node.js HTTPS request. The request goes to a server,which will return a JSON response. Then I want to parse the response and store it in a variable and use it with other functions.

let obj=JSON.parse(response);
return obj;

The functions I have written:

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

I hope you can help me

To do what you want you need to understand the asynchrone side of Javascript. What you do can't work because the string is updated in an asynchronous callback. I have fix the part that didn't work.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM