繁体   English   中英

在REQUEST nodejs中返回json体

[英]Return json body in REQUEST nodejs

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

但是,我的功能不是返回响应的正文。

有人可以帮我这个吗?

这是我的代码:

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

这是我的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);
  })
}
res.send(body); 

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

您可以将回调传递给getJson:

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

...并在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);
})  

}

或者直接致电:

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

问题是你正在做回报,期望路由器获得内容。

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

当你做return body; 正在返回的函数是请求的回调,并且在任何时候你都没有将正文发送到路由器。

尝试这个:

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

而这台路由器:

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

在这里,您将res参数传递给getJson函数,因此请求的回调将能够在它能够执行时立即调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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