Javascript 从函数向expressjs中的路由发送响应
我正试图在express服务器上沿路径从api返回JSON数据。我对nodejs如何处理这种操作有点困惑。我在同一个文件中有一个函数和一个路由,路由之所以有效,是因为我得到了返回的视图和控制台中需要的数据。路线和方法如下所示:Javascript 从函数向expressjs中的路由发送响应,javascript,node.js,express,Javascript,Node.js,Express,我正试图在express服务器上沿路径从api返回JSON数据。我对nodejs如何处理这种操作有点困惑。我在同一个文件中有一个函数和一个路由,路由之所以有效,是因为我得到了返回的视图和控制台中需要的数据。路线和方法如下所示: function getData() { request(url, function (error, response, body) { if (!error && response.statusCode == 200) {
function getData() {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
return response.body;
};
});
};
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'About', data: getData() });
});
我希望在对路由的响应中使用
getData()
中的数据。我原以为这样就可以了,但它只会将数据打印到控制台,我看不出问题所在。由于http请求的异步性质,这根本不可能。相反,您必须重新构造它以获得回调
function getData(callback) {
request(url, function (error, response, body) {
if (error) {
return callback(error);
}
if (response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
//return response.body;
callback(null, response.body);
} else {
callback(response.statusCode);
}
});
};
/* GET home page. */
router.get('/', function(req, res, next) {
getData(function (err, data) {
if (err) {
return next(err);
}
res.render('index', { title: 'About', data: data });
});
});
由于http请求的异步性质,这根本不可能实现。相反,您必须重新构造它以获得回调
function getData(callback) {
request(url, function (error, response, body) {
if (error) {
return callback(error);
}
if (response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
//return response.body;
callback(null, response.body);
} else {
callback(response.statusCode);
}
});
};
/* GET home page. */
router.get('/', function(req, res, next) {
getData(function (err, data) {
if (err) {
return next(err);
}
res.render('index', { title: 'About', data: data });
});
});
res.render
渲染模板化视图。您使用的是什么视图引擎以及模板中有什么?res.render
渲染模板化视图。你使用的是什么视图引擎,模板中有什么?所以这是可行的,但我仍然不清楚为什么。我想我很难接受回电。我是否应该或不应该使用回调?更改后的getData()
是用nodejs/JavaScript编写基本方法的典型方式吗?为什么我能够简单地console.log
body,但同样的方法不会返回数据?从内部函数返回不会从oute返回。所以这是可行的,但我仍然不清楚为什么。我想我很难接受回电。我是否应该或不应该使用回调?更改后的getData()
是用nodejs/JavaScript编写基本方法的典型方式吗?为什么我能够简单地console.log
body,但同样的方法不会返回数据?从内部函数返回不会从oute返回。