http request function won't return result

﹥>﹥吖頭↗ 提交于 2021-02-10 20:45:37

问题


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:


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

});


来源:https://stackoverflow.com/questions/30257377/http-request-function-wont-return-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!