簡體   English   中英

如何使用 request-promise 從 nodejs 中的 HTTP GET 請求到變量的字符串響應

[英]How to get a string response from HTTP GET request in nodejs to a varaible using request-promise

我想調用 Web 服務並獲取對變量的字符串響應。 這是我的代碼。 但是分配給變量的值是“未定義”。 任何人都可以幫助我。

const request = require('request-promise');

function web() {
  return request("https://8f41d5af.ngrok.io/webhook/testRequest")
    .then(function(response) {
      return JSON.parse(response);
    });
}

function main() {
  var y;
  web().then(function(result) {
    y = result;
  });
  console.log('response from server=>' + y)
}

您應該在設置后打印您的變量

function main() {
  var y;
  web().then(function(result) {
    y = result;
    console.log('response from server=>' + y)
  });
  // this line executes before the value is set as it is set asynchronously 
  //console.log('response from server=>' + y)
}

您還可以確保正確鏈接承諾。

function web() {
  return request("https://8f41d5af.ngrok.io/webhook/testRequest")
    .then(function(response) {
      //return JSON.parse(response);
      return Promise.resolve(JSON.parse(response));
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM