http请求函数不会返回结果

时间:2015-05-15 10:36:50

标签: javascript node.js function express requestjs

我正在使用Express.js设置服务器,我想要一个' GET'要求' /'返回函数的结果。该函数正在从新闻API发出get请求。当我打电话给' /'时,该功能正在被触发,结果('故事')正在控制台中记录,但响应中没有发送任何内容到' /' ' GET'请求。 我已经尝试过“回归”了。声明在几个不同的地方,它仍然没有工作...任何想法将非常感谢!谢谢!

app.js

var express = require('express');
var app = express();
var stories = require('./stories.js')


app.get('/', function(req, res){
  var returnedStories = stories.searchStories();
  res.send(returnedStories);
})

var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('going live on port', host, port);

});

stories.js

var request = require('request');




function searchStories(){
  var stories = '';
  request({
    url:'http://content.guardianapis.com/search?q=christopher%20nolan&api-key=3th9f3egk2ksgp2hr862m4c9',
    json: true},
     function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body.response.results) ;
      stories = body.response.results;
      return stories;
    }
  })
};


module.exports = {
  searchStories: searchStories
  }

1 个答案:

答案 0 :(得分:2)

这是一个异步问题。执行searchStories时,res.send函数未完成。

您可以使用promise(https://www.promisejs.org)或回调。我会给你一个回调的例子。

stories.js

module.exports.searchStories = function (callback) {
  var stories;

  // GET your stories then execute the callback with the result

  stories = [
    {id: 1, name: "story 1"},
    {id: 2, name: "story 2"}
  ];

  callback(stories);
}

app.js

var express = require('express');
var app = express();
var stories = require('./stories.js')


app.get('/', function(req, res){
  stories.searchStories(function (returnedStories) {
    res.send(returnedStories);
  });
})

var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('going live on port', host, port);

});