我尝试调用Web端点(clk.example- api.com/berlin/clk/bikes/eBike20131127000a)。带有JSON的Webpoint响应:
{
"geo": {
"latitude": 52.520278,
"longitude": 13.415712
},
"connection": {
"connected": false,
"since": "2017-06-20T14:55:15.280Z"
},
"mileage": 29382,
"vin": "eBike20131127000a",
"fuelLevel": 46,
"batteryLevel": 5.424346,
"light": false,
"charging": false,
"pedalForce": 0,
"speed": 0,
"batteryVoltageBike": 48742
}
我为此写的代码是:
function httpGet(myData, callback) {
console.log("got to the http function");
// Update these options with the details of the web service you would like
to call
var options = {
//the endpoint i call for example:
//clk.example-api.com/berlin/clk/bikes/eBike20131127000a
host: 'clk.example-api.com',
path: '/berlin/clk/bikes/' + encodeURIComponent(myData),
method: 'GET'
};
var req = http.request(options, res => {
res.setEncoding('utf8');
var returnData = "";
res.on('data', chunk => {
returnData = returnData + chunk;
});
res.on('end', () => {
// we have now received the raw return data in the returnData
variable.
// We can see it in the log output via:
// console.log(JSON.stringify(returnData))
// we may need to parse through it to extract the needed data
console.log(returnData);
callback(returnData); // this will execute whatever function the
caller defined, with one argument
});
});
req.end();
}
我实际上希望Item fuelLevel存储到returnData中。也许有人可以帮助我摆脱这种局面。我没有胶水如何待办事项。 谢谢。
答案 0 :(得分:0)
以下示例使用request
模块,这是一个非常常见的模块(上个月下载量为2500万),用于节点内的api调用。
您需要安装请求npm install request
https://www.npmjs.com/package/request
var request = require('request');
function httpGet(myData, callback) {
request('http://www.mocky.io/v2/' + encodeURIComponent(myData), function (error, response, body) {
if (error) {
return callback(error);
}
var info = JSON.parse(body);
const fuelLevel = info.fuelLevel;
callback(null, fuelLevel);
});
}
function completed(err, data){
if (err){
console.log(err)
}
console.log(data);
}
httpGet('594bbf6e1200004111424b7d', completed)