[英]Making multiple Https requests with different methods in Node.js
我想發出一個返回json數據的POST請求,然后我想獲取一些鍵值,然后創建一個json字符串,然后將json插入網址。 理想情況下,這希望每30秒發生一次。 我在這里設置了一些代碼https://runkit.com/lukejamison/5d2dfbf99644eb0013c64a56
var GeoJSON = require("geojson");
const stringify = require("json-stringify-pretty-compact");
var apikey = process.env.xapikey;
var options = {
method: 'POST',
url: 'https://app.detrack.com/api/v1/vehicles/view/all.json',
headers: {
'x-api-key': apikey,
}
};
exports.endpoint = function(httpRequest, response) {
if (!apikey){
return response.end('"xapikey" key is missing.');
}
request(options, function (error, httpResponse, body){
try{
var jsonresponse = JSON.parse(body)
var lat1 = jsonresponse.vehicles[0].lat
var lng1 = jsonresponse.vehicles[0].lng
response.end(stringify({ geometry: { type: "Point", coordinates: [lng1, lat1]}, type: "Feature", properties:{}}));
}catch(ex){
response.end(ex.toString());
}
});
}
考慮到您的用例,在POST請求成功響應后,同步/異步執行PUT請求。
var request = require('request');
var GeoJSON = require("geojson");
const stringify = require("json-stringify-pretty-compact");
var apikey = process.env.xapikey;
//To create vehicle
function createVehicle(callback) {
var options = {
method: 'POST',
url: 'https://app.detrack.com/api/v1/vehicles/view/all.json',
headers: {
'x-api-key': apikey,
}
};
request(options, function (error, httpResponse, body){
if(error) return callback(error);
try{
var jsonresponse = JSON.parse(body)
var lat1 = jsonresponse.vehicles[0].lat
var lng1 = jsonresponse.vehicles[0].lng
const result = { geometry: { type: "Point", coordinates: [lng1, lat1]}, type: "Feature", properties:{}};
callback(null, result);
}catch(ex){
callback(ex)
}
}
}
//To update vehicle
function updateVehicle(data, callback) {
var options = {
method: 'PUT',
url: '',
headers: {
'x-api-key': apikey,
},
body: data
};
request(options, function (error, httpResponse, body){
if(error) return callback(error);
try{
callback(null, body);
}catch(ex){
callback(ex)
}
}
}
exports.endpoint = function(httpRequest, response) {
if (!apikey){
return response.end('"xapikey" key is missing.');
}
//To Create Vehicle
createVehicle((error, createVehicleResponse) => {
if(error) {
response.end(error.message);
}
//To Update Vehicle synchronously, enpoint will return response once updateVehicle call responded back
updateVehicle(createVehicleResponse, (error, updateVehicleResponse) => {
if(error) {
response.end(error.message);
}
response.end(stringify(createVehicleResponse));
});
/*
In order to exectue asynchronously, use the following snippet, which will retrun response after the createVehicle call the call updateVehicle in background
createVehicle((error, createVehicleResponse) => {
if(error) {
response.end(error.message);
}
updateVehicle(createVehicleResponse, (error, updateVehicleResponse) => {});
response.end(stringify(createVehicleResponse));
})
*/
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.