node.js Error: connect ECONNREFUSED; response from server - javascript

I have a problem with this little program:
var http = require("http");
var request = http.request({
hostname: "localhost",
port: 8000,
path: "/",
method: "GET"
}, function(response) {
var statusCode = response.statusCode;
var headers = response.headers;
var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
console.log(statusLine);
for (header in headers) {
console.log(header + ": " + headers[header]);
}
console.log();
response.setEncoding("utf8");
response.on("data", function(data) {
process.stdout.write(data);
});
response.on("end", function() {
console.log();
});
});
The result in console is this:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
I do not understand why this happens.

From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).
The problem might be you have not created server on your local machine which listens to port 8000.
For that you have to set up server on localhost which can serve your request.
Create server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run server.js : node server.js
Run file that contains code to make request.

Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});

I solved this problem with redis-server, you can install that like this!
sudo apt-get install redis-server
after that see the port and change it!

I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

Just run the following command in the node project:
npm install
Its worked for me.

i ran the local mysql database, but not in administrator mode, which threw this error

If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.

I got this error because my AdonisJS server was not running before I ran the test. Running the server first fixed it.

If this is the problem with connecting to the redis server (if your redis.createClient function does not work although you are sure that you have written the right parameters to the related function), just simply type redis-server in another terminal screen. This probably gonna fix the issue.
P.S.: Sorry if this is a duplicate answer but there is no accepted answer, so, I wanted to share my solution too.

This is very slight error. When I was implementing Event server between my processes on nodejs.
Just check for the package you're using to run your server like Axios.
Maybe you might have relocated the files or disconnected some cache data on the browsers.
It's simple ,In your relevant directory run the following command
I was using axios so I used
npm i axios
Restart the server
npm start
This will work.

use a proxy property in your code it should work just fine
const https = require('https');
const request = require('request');
request({
'url':'https://teamtreehouse.com/chalkers.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = body;
console.log(data);
}
}
);

Related

npm project behind a corporate proxy global

I found already a lot of helpful tutorials to set the proxy locally and global to install packages and so on.
Now I started a new project and I figured out how to reuse the proxy settings:
#! /usr/bin/env node
var http = require("http");
var shell = require('shelljs');
var request = require('request');
var iplocation = require('iplocation')
// setup proxy
var proxyUrl = shell.exec('npm config get proxy', {silent:true}).stdout;
var proxiedRequest = request.defaults({
'proxy': proxyUrl,
'https-proxy' : proxyUrl,
'strict-ssl' : false
});
// get location (works)
proxiedRequest('http://ipinfo.io/216.58.194.46', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
// doesn't work
iplocation('56.70.97.8').then(res => {
console.log(res.iplocation)
})
.catch(err => {
console.error(err);
})
Is there a way to set it someway global for the project so other npm packages could use it too?
I tried a local .npmrc file in the projects folder but it doesn't affect the environment at all.
Any hints are welcome. Thanks
This SO answer1, SO answer2 explains different ways to set npm proxy. See if it helps you.
You could add functions like proxy_on and proxy_off to your bashrc which will let you set global npm config and toggle it from your command line.
Refer to this gist for the code.

Error: connect ECONNREFUSED node.js https.get request

I'm running the following in a small test node project.
var https = require('https');
var request = https.get('https://example.com/script.json', function(response){
console.dir(response);
});
request.on('error', function(){
console.log(err);
});
When I try to console.dir the response I get the following error.
throw er; // Unhandles 'error' event
Error: connect ECONNREFUSED xxx.xx.xxx.xx:xxx
It's a simple get request to a json file on an external server. I know the file exists so I'm not sure why I'm getting the above error. The file can be run in the browser and requires no authentication.
UPDATE: I edited the code. created a promise and added an .on('error'... to catch any issues.
The following is now output:
( [Error: connect ECONNREFUSED xxx.xx.xxx.xx:xxx]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: 'xxx.xxx.xxx.xxx',
port: 443 )
Thanks to help from #robertklep I came up with the following solution which allows me to connect to HTTPS from behind a proxy using request
const https = require('https');
const request = require('request');
request(
{
'url':'https://https://example.com/script.json',
'proxy':'http://xx.xxx.xxx.xx'
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
The other server is not up, or not listening to 443 port so you get a connection refused.
Another option is that the nodejs app is resolving that example url differently to a different ip than your pc.

Http-proxy hangs up all the time

I have a JavaScript proxy server that often hangs up after having used it a while. This is the proxy code:
var express = require(["express"], function(){}),
http = require(["http"], function(){}),
port = (process.env.PORT || 8001),
server = module.exports = express(),
httpProxy = require(['http-proxy'], function(){});
var proxy = httpProxy.createProxyServer();
// SERVER CONFIGURATION
// ====================
server.configure(function() {
server.use(function(req, res, next) {
if (req.url.indexOf('/any/thing') === 0) {
//console.log(res);
proxy.web(req, res, {target: 'http://any.thing.com'});
} else {
next();
}
});
server.use('/anything', express["static"](__dirname + "/../public"));
server.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
server.use(express.bodyParser());
server.use(server.router);
});
// Start Node.js Server
http.createServer(server).listen(port);
I am trying to do some tests with Nightwatch.js. The tests work up to a point, then the server crashes. In some tests this point is always reached at the same time, in others it depends when the server crashes and if it crashes at all.
This is the Error message:
C:...\node_modules\http-proxy\lib\http-proxy\index.js:119
throw err;
^
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketCloseListener (_http_client.js:247:23)
at Socket.emit (events.js:129:20)
at TCP.close (net.js:485:12)
Stopping Express server
What could be the reason for this? I was not able to figure it out in google.
The error is thrown when parallelly sending requests to the http-proxy.
The error can be prevented by installing a different version of http-proxy.
For me the error occured in http-proxy version 1.6.2.
I fixed the problem by installing version 1.0.0:
npm uninstall http-proxy
then
npm install http-proxy#1.0.0

"Object is not a function" when passing a Node.js HTTP server object to Socket.IO

This was working a few months ago when I was creating an HTTPS server, but I switched to http (not sure this switch is directly related, just mentioning it in case) today when revisiting this application, where I create a server and pass it to socket.io:
init.js
var server = require(dirPath + "/custom_modules/server").serve(80);
var socket = require(dirPath + "/custom_modules/socket").socket(server);
It is important that I pass the server to socket.io (I know there are alternate ways of initializing the socket) this way because that's how it has to be done in order to encrypt the websocket connection when I switch back to serving HTTPS later.
So my server module:
//serve files
module.exports.serve = function(port) {
//var server = https.createServer(options, function(req, res) { // SSL Disabled
var server = http.createServer(function(req, res) {
// Parse & process URL
var reqInfo = url.parse(req.url, true, true), path = reqInfo.pathname;
// Quickly handle preloaded requests
if (preloaded[path])
preloadReqHandler(req, res, preloaded[path], path);
// Handle general requests
else
generalReqHandler(req, res, reqInfo);
}).listen(port);
return server; //this should be returning an http server object for socket.io
};
and my socket module:
module.exports.socket = function(server) {
//create socket
var socket = require(dirPath + '/node_modules/socket.io')(server);
// ^ error
// .. snip ..
//handle client connection
socket.on("connection", function(client) {
// .. snip ..
});
};
and my error:
/home/ec2-user/Sales_Freak/server/custom_modules/socket.js:17
var socket = require(dirPath + '/node_modules/socket.io')(server);
^
TypeError: object is not a function
at Object.module.exports.socket (/home/ec2-user/Sales_Freak/server/custom_modules/socket.js:17:59)
at Object.<anonymous> (/home/ec2-user/Sales_Freak/server/init.js:16:59)
Assume all of the necessary Node.JS modules are required properly above. What silly mistake am I making today?
The exported module is not a function, refer to your previous statement:
var socket = require(dirPath + "/custom_modules/socket").socket(server);
And compare that to your current statement:
var socket = require(dirPath + '/node_modules/socket.io')(server);
I think you meant to do this instead.
var socket = require(dirPath + '/node_modules/socket.io').socket(server);
This might or might not be helpful to others, but my problem was that I changed the directory of my Node.js server files and socket.io wasn't installed in the new location.
The module was there in node_modules but not installed. I'm actually not sure how installation works with npm modules, but the module existed and therefore didnt throw an error saying it didnt exist, but did not act like it was really there until I did npm install socket.io
If you get this error in this situation, you forgot install socket.io.

Open a Websocket connection from Meteor.js

How can we open a Websockets connection from Meteor?
Can we do something like:
ws = new WebSocket('ws://localhost/path');
ws.on('open', function() {
ws.send('something');
});
ws.on('message', function(message) {
console.log('received: %s', message);
});
Error: ReferenceError: WebSocket is not defined
Using socket.io npm package
var io = Meteor.require('socket.io')
var socket = io.connect('http://localhost');
Error: TypeError: Object # has no method 'connect'
Using ws npm package
var WebSocket = Meteor.require('ws');
var ws = new WebSocket('ws://localhost');
Error: Error: Cannot find module '../build/default/bufferutil'
I created a new Meteor package joncursi:socket-io-client to solve this problem. Please see https://atmospherejs.com/joncursi/socket-io-client for more detail and example usage. Since I've bundled the NPM binaries into a package for you, you don't have to worry about installing NPM packages, declaring NPM.require() dependencies, etc. And best of all, you can deploy to .meteor.com without a hitch.
There is a package called Meteor Streams, that can let you do something similar, using the existing meteor websocket to connect to the local server:
chatStream = new Meteor.Stream('chat');
if(Meteor.isClient) {
sendChat = function(message) {
chatStream.emit('message', message);
console.log('me: ' + message);
};
chatStream.on('message', function(message) {
console.log('user: ' + message);
});
}
I'm not sure you wanted to connect to another server or the local one, if its another one you can use the example you have provided. I would recommend using something else like SockJS or socket.io in the case where websockets aren't permitted on the client side (and hence websocket emulation is required).
According to this question's answer which refers to an openshift blog post,
you answer is:
(question : How to set Meteor WebSocket port for clients?)
I struggled with this for a while now and I tried different things.
The solution that worked for me in OpenShift was this:
Set the DDP_DEFAULT_CONNECTION_URL variable
//for http
process.env.DDP_DEFAULT_CONNECTION_URL = 'http://' + process.env.OPENSHIFT_APP_DNS + ':8000'
//for ssl
process.env.DDP_DEFAULT_CONNECTION_URL = 'https://' + process.env.OPENSHIFT_APP_DNS + ':8443'
According to this blog post:
https://www.openshift.com/blogs/paas-websockets
You can try here is the solution:
https://github.com/Akryum/meteor-socket-io

Categories