Javascript 在 REQUEST nodejs 中返回 json body

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26721994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:17:03  来源:igfitidea点击:

Return json body in REQUEST nodejs

javascriptjsonnode.jshttprequest

提问by Hirad Roshandel

I'm using the requestmodule to make an HTTP GET request to an url in order to get a JSON response.

我正在使用该request模块向 url 发出 HTTP GET 请求以获取 JSON 响应。

However, my function is not returning the response's body.

但是,我的函数没有返回响应的正文。

Can someone please help me with this?

有人可以帮我解决这个问题吗?

Here is my code:

这是我的代码:

router.get('/:id', function(req, res) {
  var body= getJson(req.params.id);
  res.send(body);
});

Here is my getJsonfunction:

这是我的getJson功能:

function getJson(myid){
  // Set the headers
  var headers = {
   'User-Agent':       'Super Agent/0.0.1',
   'Content-Type':     'application/x-www-form-urlencoded'
  }
  // Configure the request
  var options = {
    url: 'http://www.XXXXXX.com/api/get_product.php',
    method: 'GET',
    headers: headers,
    qs: {'id': myid}
  }

  // Start the request
  request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    return body;
  }
  else
    console.log(error);
  })
}

回答by Michael Anthopolous

res.send(body); 

is being called before your getJson() function returns.

在 getJson() 函数返回之前被调用。

You can either pass a callback to getJson:

您可以将回调传递给 getJson:

getJson(req.params.id, function(data) {
    res.json(data);
});

...and in the getjson function:

...在 getjson 函数中:

function getJson(myid, callback){
// Set the headers
var headers = {
'User-Agent':       'Super Agent/0.0.1',
'Content-Type':     'application/x-www-form-urlencoded'
}
// Configure the request
var options = {
url: 'http://www.XXXXXX.com/api/get_product.php',
method: 'GET',
headers: headers,
qs: {'id': myid}
}

// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
    callback(body);
}
else
    console.log(error);
})  

}

or simply call:

或者干脆打电话:

res.json(getJson(req.params.id));

回答by chris-l

The problem is that you are doing a return, expecting that the router will get the content.

问题是你正在做一个返回,期望路由器会得到内容。

Since is an async callback, that will not work. You need to refactor your code to be async.

由于是异步回调,因此不起作用。您需要将代码重构为异步。

When you are doing return body;the function that is being returned is the callback of request, and in no part you are sending the body to the router.

当您执行return body;返回的函数是请求的回调时,您绝不会将主体发送到路由器。

Try this:

尝试这个:

function getJson(myid, req, res) {
  var headers, options;

  // Set the headers
  headers = {
    'User-Agent':       'Super Agent/0.0.1',
    'Content-Type':     'application/x-www-form-urlencoded'
  }

  // Configure the request
  options = {
    url: 'http://www.XXXXXX.com/api/get_product.php',
    method: 'GET',
    headers: headers,
    qs: {'id': myid}
  }

  // Start the request
  request(options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      res.send(body);
    } else {
      console.log(error);
    }
  });
}

And this router:

还有这个路由器:

router.get('/:id', function(req, res) {
  getJson(req.params.id, req, res);
});

Here, you are instead passing the resparam to the getJsonfunction, so the callback of request will be able to call it as soon as its able to do it.

在这里,您将res参数传递给getJson函数,因此请求的回调将能够尽快调用它。