2017-03-03 137 views
0

我對Node.js HTTPS請求有疑問。 請求發送到服務器,該服務器將返回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; 
    } 

我希望你能幫助我

回答

4

要做到你需要了解的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

+0

非常感謝您! 現在我有一個新的問題 我必須等待一個令牌,直到收到它,然後執行我的代碼的其餘部分。 但是我無法等到服務器響應我的請求。我怎樣才能做到這一點? –

+0

最簡單的方法是在第一個請求的回調中創建下一個請求,但我建議你看看異步函數,它們可以幫助你很多。並檢查像請求承諾的庫。 – NBeydon