http请求函数不会返回结果 [英] http request function won't return result
问题描述
我正在使用Express.js设置服务器,并且希望对'/'发出'GET'请求以返回函数的结果.该函数正在从新闻API发出获取请求.当我调用"/"时,该函数被触发,结果(故事")被记录在控制台中,但是对"/""GET"请求的响应中没有任何发送.我尝试将"return"语句放在几个不同的位置,但仍然无法正常工作……任何想法将不胜感激!谢谢!
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
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
}
推荐答案
这是一个异步问题.当您执行 res.send
时, searchStories
函数未完成.
It's an asynchronous problem. searchStories
function is not finish when you execute res.send
.
您可以使用promise( https://www.promisejs.org )或回调.我会给你一个回调的例子.
You can use promise (https://www.promisejs.org) or a callback. I'll give to you an example with callback.
stories.js
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);
});
这篇关于http请求函数不会返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!