timeout error handling with node.js and express - node.js

In my app using node.js and Express I've got a problem with handling timeout error during my request to some 3rd party shop's url. Sometimes shop's server is overloaded and I get a timeout error.
That's my code:
request(url, function (error, response, html) {
console.log("response.statusCode: " + response.statusCode);
if (!error && response.statusCode == 200) {
console.log("OK");
//some code
}
});
I managed to handle errors like 404 but I don't know how to handle timeout connection error. I've read about connect-timeout module for node.js, but I think it is more for for 'in app' requests, rather than for request to 3rd party url. Do I think correctly? What does time after which I get timeout error depends on?

Related

Google sheets api 500 INTERNAL error Node Js

Hello i'm using sheets v4 in my nodejs application everything works good for the majority of users but for some users using the service they always get INTERNAL status error
what's the meaning of this status and how can i fix it.
here's the error message:
{"code":500,"message":"Internal error encountered.","status":"INTERNAL"}
here's my code:
getSpreadsheetValues(tokens, ssID, SheetName, range, callback){
request({
url: 'https://sheets.googleapis.com/v4/spreadsheets/'+ssID+'/values/'+SheetName+'!'+range+'?access_token='+tokens.access_token,
method: 'GET'
}, function(error, response, body){
var body = JSON.parse(body)
callback(body.error, body.error ? "":body);
});
}
The API has a default quota of 100 reads/day. After that it throws a meaningless error message such as Internal Error Encountered. I suddenly encountered these errors, even though I didn't change any of my code [github].
You can put a 100 second delay every 100 requests.

node request module - sample request failing

I'm currently using node 7.6.0 and am trying the npm request module 2.80.0. The module is installed via package.json npm install. Following their simple example I immediately get: "Failed: Cannot set property 'domain' of undefined". Its a straight copy paste except for the require part.
var request = require('../node_modules/request/request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
Am I missing something or is there other dependencies I'm not aware of?
I required it incorrectly. Should just be node_modules/request. Confusing since there is an actual request.js inside the request folder with a module exports.
// Exports
Request.prototype.toJSON = requestToJSON
module.exports = Request

How to retrieve data from API using nodejs coffeescript

I have an API and i want to retrieve API data.I am using nodeJS and
coffeescript.How can i write nodejs script using coffeescript.Here is
my API and want to retrieve data from that API.Please help me.
http://apiprod.yourstory.com/v1/site/YOURSTORY/articles/
Please try to install request package using npm and use below code :
var request = require('request');
//Lets try to make a HTTP GET request to modulus.io's website.
request('http://www.modulus.io', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Show the HTML for the Modulus homepage.
}
});
Below link explains in more detail :
http://blog.modulus.io/node.js-tutorial-how-to-use-request-module

Testing Node.js api with mocha

I am busy building functional tests for an existing nodejs api I wrote. I am using mocha and expect.js.
One test that is failing is when I want to do a negative test for the existence of a url parameter. What I want is to send a message back to the the consumer of the service if the param is missing.
Currently the positive test I have works:
var request = require('request');
it('get a specific user from the api', function (done) {
request.get('http://localhost:8080/api/v1/user/123', function (error, response, body) { ... });
});
However, the following does not work and all I get is a timeout:
it('should return a 400 message if UserId is not supplied stating that "UserId expected"', function(done) {
request.get('http://localhost:8080/api/v1/user/', function (error, response, body) {
if (!error && response.statusCode == 400) {
expect(body).to.be.equal('UserId expected');
done();
}
});
});
Both the above tests are testing this endpoint:
app.get('/api/v1/user/:userid', function (req, res) {
if(!req.params.userid) {
return res.status(400).json('UserId expected');
}
... get the user and return it with status 200 ...
});
However, as stated before, the first test is successful while the second test times out.
Update 1:
Additionally, I am getting the following output:
GET /api/v1/user/123 200 2.905 ms - 274
GET /api/v1/user/ - - ms - -
Update 2:
So adding the following code solves the problem, but doesn't really solve the problem:
app.get('/api/v1/user', function (req, res) {
return res.status(400).json('UserId expected');
});
Obviously I don't want a rather redundant piece of code sitting around. I am baffled as to why I cannot enter the 'api/v1/user/:userid' endpoint and just test for the existence of :userid in there? It's as if nodejs is requiring the existence of :userid, otherwise the endpoint does not exist. Is this correct?
What am I missing?
According to mocha documentation the done callback must always be called, also in case of errors. In fact it accepts an error.
So I think that you must rewrite your code with:
it('should return a 400 message if UserId is not supplied stating that "UserId expected"', function(done) {
request.get('http://localhost:8080/api/v1/user/', function (error, response, body) {
if (error) return done(error);
if (response.statusCode != 400) return done(new Error("Not 400"));
expect(body).to.be.equal('UserId expected');
done();
});
});
So I did some more investigation and asked another question regarding this issue here.
In the end the issue was that I didn't fully understand the express framework. Basically what I alluded to in Update 2 of my question is the route I will need to follow and specify a route where no param is expected, but return the error message I am expecting in that case.
The problem I have with this approach is that in some instances one might want to use more than one parameter in the ur. However, this will mean the permutations to cater for each scenario where a parameter is undefined gets a bit daunting. (2 params will mean 4 combinations, 3 will mean 9 etc.) This will be a maintenance nightmare!
My approach from now on will be to rather follow an approach where any info I want to pass to the server will be sent via JSON in the body from of each request. This will allow me to keep to one single route.

596 Service not found while using ESPN API

I am using this API to consume a ESPN API:
http://api.espn.com/v1/now?apikey=d4skkma8kt2ac8tqbusz38w6
In Node.js, using node-curl library, my snippet looks like this:
var Curl = require('node-curl/lib/Curl')
curl.setopt('URL', url);
curl.setopt('CONNECTTIMEOUT', 2);
curl.on('data', function(chunk) {
console.log(chunk);
});
But everytime when I run this code I keep on getting response as:
<h1>596 Service Not Found</h1>
Strange is, same URL if I hit from the browser I get the correct response so URL is not invalid. This happens only if I try to call from Node.js. Can anyone guide me how to resolve this error? I tried encoding/decoding url, still I get same response.
Also basically I am avoiding any vendor specific libraries as much as possible, since we should have generic api calling framework
You could use request, which is a very popular module. Here's an example of how you could do it:
var request = require('request');
var url = 'http://api.espn.com/v1/now?apikey=d4skkma8kt2ac8tqbusz38w6';
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body));
}
});

Resources