Coffeescript HTTP client - node.js

I am running server.coffee from this page: https://github.com/xenph/foaas
From the command line, you can do:
curl http://localhost:5000/off/Name1/Name2
!##$ off, Name1. - Name2
But I'm using the code from this page: http://coffeescriptcookbook.com/chapters/networking/basic-http-client
http = require 'http'
http.get { host: 'http://localhost:5000/off/Name1/Name2' }, (res) ->
data = ''
res.on 'data', (chunk) ->
data += chunk.toString()
res.on 'end', () ->
console.log data
The error I get is:
events.js:72
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
Which leads me to believe that it's not finding the url.
What can I do?

try
http.get 'http://localhost:5000/off/Name1/Name2', (res) ->
or
http.get { hostname: 'localhost', port: 5000, path: '/off/Name1/Name2' }, (res) ->
instead of
http.get { host: 'http://localhost:5000/off/Name1/Name2' }, (res) ->
maybe?

Firstly extract a little more info from exceptions:
.on('error',function(e){
console.log("Error: " + hostNames[i] + "\n" + e.message);
console.log( e.stack );
});
Secondly as curl is working we can assume that the service is up and accessible from localhost so there must be a deeper issue. What flavour of linux are you using? I've solved similar issues before by disabling firewall (iptables) and selinux.
Also double check to make sure that you have dns configured and that it will return 127.0.0.1 for localhost. Use nslookup.

Related

getting Error: getaddrinfo ENOTFOUND while performing rest api call in node.js using http.request

i have created api in node.js which consume set of api hosted at http://dev.abc.co.in:20081
not every time but randomly sometimes it throws the error
Error: getaddrinfo ENOTFOUND dev.abc.co.in
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) {
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'dev.abc.co.in'
}
to call those api i have used request node module because i started getting this error i switched to fetch-node npm module and finally replace the code with internal node module http but getting same error
here is the code i have written using http.request
try{
const options = {
hostname: "dev.abc.co.in",
port : 20081,
path: "/api/entity/workorder",
method: Config.method
};
if(Config.headers){
options.headers = Config.headers
}
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
callback(res, data);
});
req.socket.destroy();
}).on("error", (err) => {
console.log("===Error: ", err);
callback(null, err);
});
if(Config.method!="GET" && Config.body){
Config.headers["Content-Length"] = Config.body.length;
req.write(Config.body);
}
req.end();
}catch(e){
console.log("Exception=====",e);
}
as shown in error message issue related to DNS so i try to resolve this DNS using
node -pe 'require("dns").lookup("dev-vsg.dovertech.co.in",function(){console.dir(arguments)})
but still not resolved.
1) Omit 'http://' from the beginning of your demain and all slashes from the end or any path after the actual domain.
2) Try to resolve your hostname:
const dns = require('dns');
dns.resolve("testdomain.com", 'ANY', (err, records) => {
if (err) {
console.log("Error: ", err);
} else {
console.log(records);
}
});
If dns records has been returned, then you will know it's a node js problem and after that we can investigate further. If not, then it's a domain configuration issue.

Sync gateway connection Error: connect EMFILE - Local (undefined:undefined)

I am trying to get couchbase document revision identifier via sync gatetway API GET /{db}/{doc} within Node server:
function _getRev(docIdUrl, gateway, callback) {
let options = {
host: gateway.host,
path: gateway.path + docIdUrl,
port: gateway.port,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
// Node HTTP requests
let syncGatewayRequest = http.request(options, (response) => {
// ...unrelevant codes
});
syncGatewayRequest.on('error', (error) => {
logger.error('syncGateway connection error for ' + docIdUrl);
callback(error, null); // here is the error happening!!!!!
});
syncGatewayRequest.write(JSON.stringify({}));
syncGatewayRequest.end();
}
Then I got error:
[2017-11-03 11:07:51.961] { [Error: connect EMFILE 10.0.1.53:4985 - Local (undefined:undefined)]
code: 'EMFILE',
errno: 'EMFILE',
syscall: 'connect',
address: '10.0.1.53',
port: 4985 }
Error: connect EMFILE 10.0.1.53:4985 - Local (undefined:undefined)
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at connect (net.js:849:16)
at net.js:937:9
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
There is a context that the above function are executed asynchronously by a significant number of services, say 10,000+
I noticed the post here Nodejs connect EMFILE - How to reuse connections?
But I tried to unlimit the default connections by doing:
var http = require('http')
http.globalAgent.maxSockets = Infinity
But does not seem to work, error still ...
Anyone can let me know what's wrong here?

What could cause "connect ETIMEDOUT" error when the URL is working in browser?

I train myslef with NodeJS and tried a simple GET call.
Here is my code:
var http = require('http');
var options = {
host: 'www.boardgamegeek.com',
path: '/xmlapi/boardgame/1?stats=1',
method: 'GET'
}
var request = http.request(options, function (response) {
var str = ""
response.on('data', function (data) {
str += data;
});
response.on('end', function () {
console.log(str);
});
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
});
request.end();
The URL called seems to work in my browser https://www.boardgamegeek.com/xmlapi/boardgame/1?stats=1
Anyway, I've got Problem with request: connect ETIMEDOUT when I run the code and I have no idea how to fix it.
What could cause this error ? Is it my code or is it a network/proxy issue?
When behind a proxy you need to make the following modifications (as explained in this answer):
put the proxy host in the host parameter
put the proxy port in the port parameter
put the full destination URL in the path parameter :
Which gives:
var options = {
host: '<PROXY_HOST>',
port: '<PROXY_PORT>',
path: 'http://www.boardgamegeek.com/xmlapi/boardgame/1?stats=1',
method: 'GET',
headers: {
Host: 'www.boardgamegeek.com'
}
}
In my case it was because of http but not https as required
If this error occurs while using POSTMAN.
So, when you call a request in Postman and the API requires your VPN to be up before you can make a successful call. You will need to connect or reconnect your VPN.
In my case, I was working on a company's laptop. I found out it was the VPN that was down.
The following change with the request worked for me:
var options = {
proxy:'PROXY URL',
uri: 'API URL',
method: 'GET'
}
request(options, function (err, response, body) {
if(err){
console.log('error:', err);
} else {
console.log('body:', body);
}
});
In my case it was a misconfigured subnet. Only one of the 2 subnets in the ELB worked. But my client kept trying to connect to the misconfigured one.
if you have URL
like :
URL: 'localhost:3030/integration',
The URL above cause some issues because HTTP does not exist at the beginning of URL so Just change it to it should work.
URL: 'http://localhost:3030/integration',
In my case, I was getting this error because the request body of my post api was very large.
I was facing this issue on Ubuntu Server while maintaining a node instance on PM2. Basically after restarting the instance after taking the pull I was getting the same error on initial connection of mySQL inside the code.
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/home/deam_server/node_modules/mysql/lib/Connection.js:419:13)
at Object.onceWrapper (events.js:275:13)
at Socket.emit (events.js:182:13)
at Socket.EventEmitter.emit (domain.js:442:20)
at Socket._onTimeout (net.js:447:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
Though the same code was running perfectly on my local machine.
After that I used "df" command which helped me to realise that my root directory was 100% occupied. I allotted some memory to the root directory and the restarted the node instance and then it started working fine.
Sometimes it can simply be because your internet is down.

Node.js Error : connect ECONN Refused

I am new to Node.js and am unable to resolve this error:
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect (as oncomplete) (net.js:892)
The code I was trying out follows :
var async = require('async'),
request = require('request');
function done(err,results) {
if (err) {
throw err;
}
console.log('Done ! results: %j',results);
}
var collection = [1,2,3,4];
function iterator(value,callback) {
request.post({
url: 'http://localhost:8080',
body: JSON.stringify(value)
}, function (err,res,body){
if (err) {
callback(err,body && JSON.parse(body));
}
});
}
async.map(collection,iterator,done);
ECONNREFUSED – Connection refused by server error
A port is being blocked can be the root cause of this issue, check if your connection is being blocked or even the changed default port can also cause this issue. Identify which app/service you are connecting to and its port is being blocked or changed.
And in your case check whether the application is hosted on port: 8080 or not.
But, this most likely occurs with FileZilla.

Getting error while using http in node.js

Below is the error getting while calling http get request
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: getaddrinfo ENOENT
at errnoException (dns.js:31:11)
at Object.onanswer [as oncomplete] (dns.js:123:16)
PFB my code throwing the error
var options = {
host: 'http://xyz.com',
port: 80,
path : 'test?query=' + escape(req.params.searchTerm) + '&offset=0&hits=500',
method: 'GET',
headers: {
Cookie : "session=" + session
}
};
console.log("Start");
var x = http.request(options,function(subRes){
console.log("Connected");
subRes.on('data',function(data){
console.log("===================data===" +util.inspect(data));
});
});
x.end();
Any ideas, why this error ?
ENOENT is an error that indications name resolution did not return any results. You specify the hostname as http://xyz.com, but colons are not allowed in hostnames. You want:
var options = {
host: 'xyz.com',
You specify the host as http://xyz.com, which should just be xyz.com.
This value is used to resolve the IP address of the host you're trying to connect to using DNS.

Resources