Ajax call to API with parameter - node.js

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.

Related

Is it possible to turn this request into an API?

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);
})
}

Trying to make an API call to a remote endpoint with NestJS

var unirest = require("unirest");
var req = unirest("GET", "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data");
req.query({
"ingr": "1 large apple"
});
req.headers({
"x-rapidapi-host": "HOST",
"x-rapidapi-key": "KEY",
"useQueryString": true
});
req.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.body);
});
Im trying to make an API call with that doc and parameters in order to get a list of ingredients based on a search parameter.
This is my service:
async getAllNutrients(ingr: string) {
console.log(ingr);
const headersRequest = {
'x-rapidapi-host': 'edamam-edamam-nutrition-analysis.p.rapidapi.com',
'x-rapidapi-key': '5664b75c9fmsh66ac8e054422eb9p1600b8jsn878d097e8d2a',
useQueryString: true,
};
const result = await this.httpService.get(
`https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data` +
ingr,
{ headers: headersRequest },
);
console.log(result);
return result;
}
And this is my controller
#Get('/list?:ingr')
getMacros(#Query('ingr') ingr) {
return this.macroService.getAllNutrients(ingr);
}
I tried to change QUery and Param but none are working.
On postman i make an API call like this:
"localhost:3000/macros/list?ingr="1 large apple"
And my 2 console.log returns:
"1 large apple"
Observable { _isScalar: false, _subscribe: [Function] }
[Nest] 7460 - 2020-09-21 16:00:55 [ExceptionsHandler] Request failed with status code 404 +441782ms
Error: Request failed with status code 404
I tried to use pipe like this example:
getQuote(id){
return this.http.get('http://quotesondesign.com/wp-json/posts/' + id)
.pipe(
map(response => response.data)
);
}
But the result was the same. Any help?
Looks like your issue is in your controllers route. Changing #Get('/list?:ingr') to #Get('/list') should resolve this. I believe passing ?:ingr in the path is setting a param with key ingr.
Queries do not need to be added to the route. They are accessed using the #Query decorator.
Look at this for more info.
In your service function
const result = await this.httpService.get(
`https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data` +
ingr,
{ headers: headersRequest },
);
with ingr is 1 large apple then the API URL will become "https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data1 large apple".
I think this is an incorrect API URL, and you don’t want to call the API like that.
Change it to
`https://edamam-edamam-nutrition-analysis.p.rapidapi.com/api/nutrition-data?ingr=${ingr}`,

how to send fetched data node js

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.

Passing the response of one API call to another API

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.

Stop multiple async calls from client Node JS Angular

I have a single page app that gets a list of objects from an node js server. However if the user selects the first item in the list before the rest of the related objects are loaded it needs to cancel the request. I can cancel the request on the client side (angular) but don't see how to cancel a request on an already started call in node !
The code below is the method i use to call the node api with the ability to cancel that request on the client side.
getDiscovery : function(ids) {
var Ids = [],
apiUrl = '/api/Something/ids',
self = this,
deferredAbort = $q.defer();
// Initiate the AJAX request.
var request = $http({
method: "get",
url: apiUrl,
params: {
ids: JSON.stringify(ids)
},
timeout: deferredAbort.promise
});
var promise = request.then(
function(response) {
return(response.data);
},
function(response) {
return($q.reject( "Something went wrong" ));
}
);
promise.abort = function() {
deferredAbort.resolve();
};
promise.finally(
function() {
console.info( "Cleaning up object references." );
promise.abort = angular.noop;
deferredAbort = request = promise = null;
}
);
return(promise);
}
This is the method on the node api which needs to be cancelled
exports.getItemsDiscovery = function(req, res){
var Items = JSON.parse(req.query.ids);
async.each(Items,
function(Item, callback){
method.getSomething(Item.Id, function(data){
console.log('Got data for', item.Id);
callback();
});
},
function(err) {
return res.send(Items);
});
};
The route is
app.get('/api/ids', something.getItemsDiscovery);
Any help would be much appreciated
Rob

Resources