1

I am setting up a server with Express.js and I want a 'GET' request to '/' to return the results of a function. The function is making an get request from a news API. When I make the call to '/', the function is being triggered, and the results ('stories') is being logged in the console, but nothing is being sent in the response to the '/' 'GET' request. I have tried putting the 'return' statement in a few different places and it still doesn't work... any idea would be hugely appreciated! thanks!

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
  }
4

1 回答 1

2

这是一个异步问题。searchStories执行时功能未完成res.send

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

故事.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);
}

应用程序.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);

});
于 2015-05-15T12:44:01.573 回答