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);
})
}
Related
I tried following these instruction but couldn't get the URI decoded. how can I go about this?
When I enter a city like http://localhost:5000/weather?weatherCity=Malmö the URL changes to this http://localhost:5000/weather?weatherCity=Malm%C3%B6,
How can I decode the last part and what am I doing wrong?
app.get('/weather', (req, res) => {
const weatherCity = (req.query.weatherCity)
let decodeURI = decodeURIComponent(weatherCity) //<------- trying to decode the query
request(weatherURL(decodeURI), function (error, response, body) {
if (error) {
throw error
}
const data = JSON.parse(body)
return res.send(data)
});
})
function weatherURL(weatherCity){
return `https://api.openweathermap.org/data/2.5/weather?q=${weatherCity}&units=metric&appid=${process.env.APIKEY}&lang=en`
}
This is probably what you need:
app.get('/weather', (req, res) => {
const weatherCity = req.query.weatherCity;
request(weatherURL(weatherCity), function (error, response, body) {
if (error) {
throw error
}
const data = JSON.parse(body)
return res.send(data)
});
})
function weatherURL(weatherCity){
return `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(weatherCity)}&units=metric&appid=${process.env.APIKEY}&lang=en`
}
There should be no need to decode req.query.weatherCity because express does this automatically.
You do need to encode weatherCity before building a URL with it. URL query parameters should be URL encoded.
Consider using something other than request because it is deprecated and doesn't support promises. node-fetch and axios, among others, are good choices.
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 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));
}
})
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.
So im completely stumped and hope someone can help with the combination of Node JS Async and Request modules. I'm attempting to build a list of file to download which I pass to Async, as an array of object contain all the information I need to download and store said file. After tons of debugging I discovered that Request are not even making there way out and I cant figure out why.
async.each(missingFiles,
function (obj, cb) {
console.log(obj.url);
//var file = nfs.createWriteStream(obj.fullPath);
request(obj.url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response)
}
cb();
})
},
function (err) {
if (err) {
console.log("Async failed");
}
}
);
I came across similar issues before. If you send response outside the async block, http request/response cycle ends before your async tasks complete. The fix is to have send response in the done() callback.
app.post("/download", function(req, res) {
async.eachSeries(missingFiles, function (obj, cb) {
...
//do your work here
cb()
}, function done() {
res.json({success: true});
});
}