我对nodeJS很新,来自.net世界。 我试图提出通用请求来质疑我的网络服务。 我会简化代码以便于理解:
var request = require('request');
var genericReq = function (apiUrl) {
// Configure the request
var options = {
url: apiUrl,
method: 'GET',
headers: headers,
}
var headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
var json;
var trackingItems = [];
// contact with web api, get list of tracking items FK
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
json = JSON.parse(body);
for (i = 0; i < json.length; i++) {
trackingItems.push(json[i].fkItemId);
}
//console.log(trackingItems);
return trackingItems;
}
else {
console.log("error connect to web api server");
}
});
}
function invokeReq() {
var value = genericReq('http://localhost:51405/api/trackingitemsapi');
console.log(value);
};
invokeReq();
当:
console.log(trackingItems);
我可以看到trackingItems数组。
然而:
function invokeReq() {
var value = genericReq('http://localhost:51405/api/trackingitemsapi');
console.log(value);
};
导致&#39; undefined&#39;