我正在尝试创建一个使用nodeJS 和express、request 返回REST API 响应的函数。 这是我的代码片段:
var express = require('express')
var httpRequest = require('request');
var bodyParser = require('body-parser');
var app = express()
function getData1() {
request('http://www.my-server.com/data', function (error, response, body) {
if (!error && response.statusCode == 200) {
return body;
}
})
}
app.get('/get-data', function (request, response) {
var data1 = getData1();
//do something with data
response.send(data1);
});
你知道我该怎么做吗?
致以诚挚的问候
最佳答案
由于 getData1
包含一个异步函数,该函数仅在完成时返回数据,只需向其中传递一个回调函数,您将在异步函数完成时调用该函数
// callback -> the function you will call later
function getData1(callback) {
request('http://www.my-server.com/data', function (error, response, body) {
if (!error && response.statusCode == 200) {
// call the function when the function finishes and also passed the `body`
return callback(body);
}
})
}
app.get('/get-data', function (request, response) {
getData1(function(data1) {
//do something with data
response.send(data1);
})
});
关于javascript - 使用函数从 REST API 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41891725/