Node - Simple xml API Request - node.js

I'm using the latest node.js (and express) to make an API call to a site that returns... XML... Ugh >_>.
I've scowered the web and found a million different ways, but I don't know the latest, most up to date / best way to make a request and get a response in node/express.
I tried using https://github.com/request/request and did the following:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
var token = request
.get('some-website.com/api/stuff')
.on('response', function(response) {
console.log(response.statusCode);
console.log(response.headers['content-type']);
});
sendJsonResponse(res, 200, token);
in the console.log statements I get 200 and then application/xml;charset=utf-8.
But on my page I don't get the xml I'm looking for. Any ideas? I've tried using https://github.com/Leonidas-from-XIV/node-xml2js to attempt to "parse" the response, in case node just can't handle the xml response, but to no avail.
var xml2js = require('xml2js');
parser.parseString(response, function(err, result) {
console.dir(result);
console.log('Done');
});
Any help on accessing an API using Node and actually using the XML response, please?
EDIT ANSWER
For the Node.js request and xml parsing of the returned xml content:
var request = require('request');
var xml2js = require('xml2js');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
/* GET XML Content*/
module.exports.dsRequest = function(req, res) {
var parser = new xml2js.Parser();
request('url_for_xml_request', function(error, response, body) {
parser.parseString(body, function(err, result) {
sendJsonResponse(res, 200, result);
});
});
};

I think this will work, because request is async, you should write like below:
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
request.get('http://some-website.com/api/stuff', function (err,response, body) {
sendJsonResponse(res, 200, body);
});

Related

How to hit third party API form node server.

IndiaSMS is a thirdparty providing sms service I want to hit this api form node server. Any way to request to third party api. Please help..
var express = require('express');
var router = express.Router();
exports.sendOTP = function (userInfo, callback) {
console.log(userInfo);
console.log('Inside SendOTP usin indaSMS');
var indiasmsURL = 'https://app.indiasms.com/sendsms/sendsms.php?username=user&password=pass&type=TEXT&sender=Alerts&mobile=' + userInfo.mobilenumber + '&message=Your%20OTP%20for%203DClubHouse%20is%20' + userInfo.otp + '';
console.log(indiasmsURL);
router.get(indiasmsURL,
function(req, res, next) {
console.log('--------------------------');
console.log(res);
console.log('--------------------------');
})
callback('hello');
};
Thnaks in advance.
This is Mikeal's request library see link here very useful
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})
Using axios:
axios.get('https://app.indiasms.com/sendsms/sendsms.php', {
params: {
username: user,
password: pass,
type: 'TEXT',
//...
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Or using async/await, you can simply:
let response = await axios.get(indiasmsURL);
if (response.status == 200) {
//console.log(`CC status ${response.status}: `, response.data)
}
You can build your URI like above (stored in indiasmsURL) or specify them in the params of the request if you would prefer.
I would suggest snekfetch or request.

node js async request cant get body of web page

I want to get the body of web-page from a list of more than 1000 urls (my goal is to do scraping using cheerio then).
The problem is that I get a weird GUNZIP result and I can't get the content of the body tag. This is the code that I'm using (I cant use a simple "request" cause it misses some request)
var async = require('async');
var fetch = require('isomorphic-unfetch');
const cheerio = require('cheerio');
let urls= // reading a list of ~1000 URLs from JSON file
async.mapLimit(urls, 1, async function(url) {
const response = await fetch(url);
return response.body
}, (err, results) => {
if (err) throw err
console.log(results);
});
The problem is that I get a weird GUNZIP result
use zlib,
var zlib = require('zlib');
async.mapLimit(urls, 1, async function(url) {
const response = await fetch(url);
zlib.gunzip(response.body, function(err, dezipped) {
return (dezipped.toString());
});
}, (err, results) => {
if (err) throw err
console.log(results);
});
then purseed your parsing with cheerio :)
i hope this helps.

Wordpress API with Express and NODEJS

Is it possible to make an external http get request from Wordpress API using express?
Let's say I want to make a get request to http://demo.wp-api.org/wp-json/wp/v2/posts - This are a list of posts from wordpress.
Sample:
router.get('/posts', function(req, res){
I should make an external http get request here from wordpress api
("http://demo.wp-api.org/wp-json/wp/v2/posts")
Then I want to display the response as json
}
Update (I figure it out):
I use the request module, so to anyone whose having trouble with it. You can call this function inside your controller:
var express = require("express");
var request = require("request");
var router = express;
var getWPPost = function(req, res){
var headers, options;
// Set the headers
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
// Configure the request
options = {
url: 'http://demo.wp-api.org/wp-json/wp/v2/posts/1',
method: 'GET',
headers: headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send({
success: true,
message: "Successfully fetched a list of post",
posts: JSON.parse(body)
});
} else {
console.log(error);
}
});
};
router.get('/post', function(req, res){
getWPPost(req, res);
}

ExpressJS - Using Q

For a certain route, I have the following code:
router.get('/:id', function(req, res) {
var db = req.db;
var matches = db.get('matches');
var id = req.params.id;
matches.find({id: id}, function(err, obj){
if(!err) {
if(obj.length === 0) {
var games = Q.fcall(GetGames()).then(function(g) {
console.log("async back");
res.send(g);
}
, function(error) {
res.send(error);
});
}
...
});
The function GetGames is defined as follows:
function GetGames() {
var url= "my-url";
request(url, function(error, response, body) {
if(!error) {
console.log("Returned with code "+ response.statusCode);
return new Q(body);
}
});
}
I'm using the request module to send a HTTP GET request to my URL with appropriate parameter, etc.
When I load /:id, I see "Returned with code 200" logged, but "async back" is not logged. I'm also not sure that the response is being sent.
Once GetGames returns something, I want to be able to use that returned object in the route for /:id. Where am I going wrong?
Since GetGames is an async function write it in node.js callback pattern:
function GetGames(callback) {
var url= "my-url";
request(url, function(error, response, body) {
if(!error) {
console.log("Returned with code "+ response.statusCode);
return callback(null,body)
}
return callback(error,body)
});
}
Then use Q.nfcall to call the above function and get back a promise:
Q.nfcall(GetGames).then(function(g) {
})
.catch()

NodeJS + miekal/request : How to abort a request?

I had been trying to abort a request for hours, can anyone help me please?
This is what I have:
app.get('/theUrl', function (req, resp) {
var parser = new Transform();
parser._transform = function(data, encoding, done) {
var _this = this;
// Process data here
}.on("error", function(err){
console.log(err);
});
var theRequest = request({
'method' : 'GET',
'url': '/anotherUrl',
'headers' : {
"ACCEPT" : "text/event-stream"
}
}, function (error, response, body){
if (error) {
//Throw error
}
}).pipe(parser).pipe(resp);
req.on("close", function(){
parser.end();
theRequest.abort(); //Doesn't work
});
});
As you can see its kinda a streaming proxy, so if clients cancels the request I catch it and need to close or abort the forwarding request (theRequest).
Any ideas?
Thanks!
Quoting nylen from https://github.com/mikeal/request/issues/772#issuecomment-32480203 :
From the docs:
pipe() returns the destination stream
so you are no longer working with a Request object. In this case you're calling abort() on a ServerResponse. Do this instead:
var theRequest = request({ ... });
theRequest.pipe(parser);
theRequest.abort();
And everything worked.

Resources