I have two urls which will add the new user and edit the user sequentially. How can I pass the output of first request to the second request as input.
http://localhost:3010/postuser
{"name":"xyz"}
// response will be unique id =>001
http://localhost:3010/putuser
{"id":001} //Get the output of first request as input here
Below is my code
function httpGet(options, callback) {
request(options,
function (err, res, body) {
callback(err, body);
}
);
}
const urls = [
{
url: 'http://localhost:3010/postuser',
method: 'POST'
},
{
url: 'http://localhost:3010/putuser',
method: 'PUT'
}
];
async.mapSeries(urls, httpGet, function (err, res) {
if (err) return console.log(err);
console.log(res);
});
Use async.waterfall so that data from one function can be passed to next function. Check the example in the link. So essentially you will call httpGet function and pass the data received from API1 to next function using callback. Then you can call the API2.
Related
I am trying to call an external REST API (dynamical URL) through a parameter in express and turn that into an API for my site(most of these APIs require being run on the web server, and won't run on the client). However, I'm not sure how exactly to go about combining this? I've been searching around on SO, but most solutions come to no success for me. I'm trying basically to:
Retrieve link from front end -> use the link to get info from API -> to use my own /getInfo API to send the data I retrieved back.
Snippet:
app.get('/api/getInfo/', (req,res) => {
const info = req.query.url;
res.send(getRest(info));
})
function getRest(url) {
Request.get(url, (error, response, body) => {
console.log(JSON.parse(body));
})
}
I'm calling it on my frontend via this method:
const GET_INFO_API = "http://localhost:3001/api/getInfo"
...
getInfo(url) {
return axios.get(GET_STEAM_API, {
params: {
url: url
}
});
}
You should be able to do it by adding a callback to the getRest function:
app.get('/api/getInfo/', (req,res) => {
const info = req.query.url;
getRest(info, (error, response, body) => {
res.send(JSON.parse(body));
});
})
function getRest(url, callback) {
Request.get(url, (error, response, body) => {
callback(error, respose, body);
})
}
Hello i have a request which fetch some json data from third party API:
request({
url: 'https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=MYAPIKEY&get_sent_offers=1&active_only=1&format=json',
json: true
}, (err, responser, body, undefined) => {
tradeItems = JSON.stringify(body.response['trade_offers_sent'][0].items_to_give);
});
How can i send tradeItems fetched data to offer.addTheirItems value?
client.on('webSession', function(sessionID, cookies) {
manager.setCookies(cookies, function(err) {
if (err) {
console.log(err);
process.exit(1);
return;
}
let offer = manager.createOffer("https://steamcommunity.com/tradeoffer/new/?partner=123456789&token=1234");
offer.addTheirItems();
offer.setMessage("");
offer.send(function(err, status) {
if (err) {
console.log(err);
return;
}
First, that's are javascript's async issue.
The solution is in many ways.
change the request function to async function. and make tradeItems variable to outside from request function.
I recommend request-promise module
move below codes to in upper code's callback function.
This is a simple answer because your sample code is separated into two parts.
I have an api route per below:
apiRouter.get('/api/getCompTeams', function(req, res) {
var compTeams = Team.find({}, {competition: 1, team:1, _id:0} ).then(eachOne => {
res.json(eachOne);
},
(fail)=> {
console.log('Error!');
},
(proceed) => {
return compTeams;
});
});
This returns all teams in the Teams collection, with the below ajax call:
async function ajaxData(url) {
var dataResults ;
try {
// AJAX CALL FOR DATA
dataResults = await $.ajax({
method: 'GET',
url: url,
dataType: 'json',
}); //AJAX CALL ENDS
return dataResults;
} // try ENDS
catch (err) {
console.log("error # ajaxData");
console.log(err.message);
} // catch ENDS
} // ajaxData ENDS
What I would like to do is to pass a parameter, with the ajax call, eg. 'La Liga', so that the apiRoute returns only teams with key:value that matches 'competition:La Liga'. I have tried various options but none have succeeded.
Any help greatly appreciated.
Using NodeJS & MongoDB.
Mosiki.
I have the following function which performs a GET call. I want to wait for the response and then perform the next step. My code looks like this
getListOfChannels : function(token, callback){
var Channels = [];
var options = { method: 'GET',
url: url,
headers:
{
'x-api-key': token } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
var json = JSON.parse(body)
var data = json.MemberEntitlement;
for(var i=0 ; i < data.length ; i++){
if(data[i].Entitled == false){
Channels.push(data[i].ChannelNumber);
}
}
});
callback(Channels[0]);
}
Also my callback function is just printing the value
simplePrint : function(arg){
console.log(arg)
}
But still, the callback function does not wait for the full response and prints out undefined.
What should i do. I can add implicit wait but that doesnt seem like a good practice.
I think you are invoking callback after the request function invocation. It's not in request's scope, but in getListOfChannels scope. Therefore, callback is running synchronously. Try replacing:
});
callback(Channels[0]);
}
with
callback(Channels[0]);
});
}
I have a simple node Express app that has a service that makesa call to a node server. The node server makes a call to an AWS web service. The AWS simply lists any S3 buckets it's found and is an asynchronous call. The problem is I don't seem to be able to get the server code to "wait" for the AWS call to return with the JSON data and the function returns undefined.
I've read many, many articles on the web about this including promises, wait-for's etc. but I think I'm not understanding the way these work fully!
This is my first exposer to node and I would be grateful if somebody could point me in the right direction?
Here's some snippets of my code...apologies if it's a bit rough but I've chopped and changed things many times over!
Node Express;
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET","http://localhost:3000/listbuckets",false);
Httpreq.send(null);
console.log(Httpreq.responseText);
return Httpreq.responseText;
Node Server
app.get('/listbuckets', function (req, res) {
var bucketData = MyFunction(res,req);
console.log("bucketData: " + bucketData);
});
function MyFunction(res, req) {
var mydata;
var params = {};
res.send('Here are some more buckets!');
var request = s3.listBuckets();
// register a callback event handler
request.on('success', function(response) {
// log the successful data response
console.log(response.data);
mydata = response.data;
});
// send the request
request.
on('success', function(response) {
console.log("Success!");
}).
on('error', function(response) {
console.log("Error!");
}).
on('complete', function() {
console.log("Always!");
}).
send();
return mydata;
}
Use the latest Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make HTTP calls. It has built-in support with Promise.
fetch('http://localhost:3000/listbuckets').then(response => {
// do something with the response here
}).catch(error => {
// Error :(
})
I eventually got this working with;
const request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
parseString(body, function (err, result) {
console.log(JSON.stringify(result));
});
// from within the callback, write data to response, essentially returning it.
res.send(body);
}
else {
// console.log(JSON.stringify(response));
}
})