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
  }
  • 1
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Ben Fortune May 15 '15 at 10:45

1 Answers1

2

It's an asynchronous problem. searchStories function is not finish when you execute res.send.

You can use promise (https://www.promisejs.org) or a callback. I'll give to you an example with callback.

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

});
LOLKFC
  • 1,065
  • 1
  • 9
  • 18