A ECONNREFUSED error of the node. Js - node.js

My Node app is throwing a ECONNREFUSED error. The port should not be in use. Any ideas?
console.info('-----http-----');
console.info();
var http = require('http');
var options = {
hostname: 'localhost',
port: 6860,
path: '/',
method: 'post'
};
var req = http.request(options, function(res) {
console.log('status:' + res.statusCode);
res.setEncoding('UTF-8');
res.on('data', function(chunk) {
console.log('body:' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request:' + e.message);
});
req.end();

Seems you are trying to send post request to one of the URL (localhost),
the code you posted that alone will not work, somewhere your server should run i.,e localhost:6860
For that just you need to create a server which runs on the port 6860.
Execute this simple server.js file in separate terminal then run "localhost:6860" in your browser.
Then run your code in separate terminal, it will execute properly. Check your both terminals you will get the difference.
**server.js**
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
console.log(req.url)
console.log(req.method)
res.end('okay');
}).listen(6860, "localhost");
$node server.js
Hope it will help you..!

Related

node js http createServer socket

The doubt with with code is two things:
When i send request through a browser, i dont get a console log message as "connected" but if i use http.get() or http.request() , it works fine
2)The "connect" event receives a callback with req,clientSocke,head ! now where can i see the server socket ?
const http=require("http")
const server=http.createServer()
server.on("connect",(req,c_socket,head)=>{
console.log("connected")
})
server.listen(5000,()=>{console.log("server up)})
when you access the server via browser, the method is using GET not CONNECT. That's why console.log does not show.
if you want console.log to show when accessing from the browser, you can use request event.
this is an explanation from node.js docs.
'connect' event is emitted each time a server responds to a request
with a CONNECT method. If this event is not being listened for,
clients receiving a CONNECT method will have their connections closed.
node.js docs
you can make a socket server with a net package with createSever method.
this is an example of how to make a simple request to the socket server.
const http = require('http');
const net = require('net');
const { URL } = require('url');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hello world');
});
server.on('connect', (req, clientSocket, head) => {
console.log('connected');
// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`);
const serverSocket = net.connect(port || 80, hostname, () => {
clientSocket.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n'
);
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
});
server.listen(5000, () => {
console.log('server up');
});
// Make a request to a tunneling server
const req = http
.request({
port: 5000,
host: 'localhost',
method: 'CONNECT',
path: 'www.google.com:80',
})
.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// Make a request over an HTTP tunnel
socket.write(
'GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n'
);
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
console.log('end');
});
});

Error: connect ECONNREFUSED. Unhandled 'error' event NodeJS

I am encountering the Nodejs error ECONNREFUSED 127.0.0.1:3000 when I try to send a get request to load a static file. I have seen many questions on this error but apparently there is no straight answer as to why this error is thrown. Here below is the code I have. I have tried changing localhost to 127.0.0.1 or change port numbers 3000, 7000, 8080 but nothing resolved it. Can someone please advised? Thank you.
//Basic web client retrieving content of file using get request
var http = require('http');
//options for request
var options = {
hostname: 'localhost',
port: '3000',
path: '../html/hello.html'
};
//function to handle response from request
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(response, error){
getResponse(response);
}).end();
Your client code is good enough to work. You are getting the ECONNREFUSED because there is a no server which is listening to the particular port number and the Server is not sending any data and you are requesting to get data from the server and accumulate it.
Here is the sample code:
//Requesting for http and fs modules
var http = require('http');
var fs = require('fs');
//creating the server and reading the file synchronously
var server = http.createServer(function(req, res) {
res.end(fs.readFileSync('./html1.html'));
}).listen(3000);
//creating the client which connects to local host at port number 3000
var options = {
hostname: 'localhost',
port: '3000',
}
//getting the data from server, storing it in to a variable, and printing at end of the data
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(response, error){
getResponse(response);
}).end();
the issue in your code , that you are not handling error, for this you have to handle error first.
var http = require('http');
var options = {
hostname: 'localhost',
port: '3000',
path: '../html/hello.html'
};
function getResponse(response){
var serverData='';
response.on('data', function(chunk){
serverData += chunk;
});
response.on('end', function(){
console.log(serverData);
});
};
http.request(options, function(error , response){
if(error){
console.log(error);//handle error here.
}else{
getResponse(response);
}}).end();

Get url and body from IncomingMessage?

I am very new to node. I am at the point at which I have a simple server which should just print the request query and the request body which it takes. What I've understood is that the "handle request" function actually doesn't return a request object, rather an IncomingMessage object.
There are two things which I don't understand: How to obtain the query string and the body.
I get just the path, without the query and undefined for the body.
Server Code:
var http = require('http');
var server = http.createServer(function (request, response) {
console.log("Request query " + request.url);
console.log("Request body " + request.body);
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
Request code:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
query: "argument=narnia",
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('response: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write("<h1>Hello!</h1>");
req.end();
Please note that I am a complete beginner. I am not looking for express only solutions.
The reason that you do not see the query string at request.url is that you aren't sending one correctly. In your request code, there is no query property of options. You must append your querystring to the path.
path: '/' + '?' + querystring.stringify({argument: 'narnia'}),
For your second question, if you want the full request body, you must read from the request object like a stream.
var server = http.createServer(function (request, response) {
request.on('data', function (chunk) {
// Do something with `chunk` here
});
});

forward proxy in nodejs

i made a small forward proxy with nodejs and hosted it in appfog.
it's working in local after setting up the proxy of my browser, but when i try using the one hosted in appfog it's says:
*Errore 130 (net::ERR_PROXY_CONNECTION_FAILED): Connessione al server proxy non riuscita.*
this is my code:
var http = require('http');
http.createServer(function(request, response) {
http.get(request.url, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}).listen(8080);
Am i missing something?
your code is working but once i've tried using it like this:
var port = process.env.VCAP_APP_PORT || 8080;
var http = require('http');
var urldec = require('url');
http.createServer(function(request, response) {
var gotourl=urldec.parse(request.url);
var hosturl=gotourl.host;
var pathurl=gotourl.path;
var options = {
host: hosturl,
port: 80,
path: pathurl,
method: request.method
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
response.write("error");
response.end();
});
}).listen(port);
console.log(port);
It's still doesn't work: i got request timed out when i try to ping the address, i got the same ERR_PROXY_CONNECTION_FAILED... locally work but when i using the remote address as proxy it doesn't
First: The app needs to use the port number issued to it by cloudfoundry. The app sits behind a reverse proxy that takes incoming requests on port 80 and forwards them to the VCAP_APP_PORT.
var port = process.env.VCAP_APP_PORT || 8080; // 8080 only works on localhost
....
}).listen(port);
Then you access your hosted app like this:
http://<app_name>.<infra>.af.cm // port 80
And your local app:
http://localhost:8080
Second: You may need to use a options hash to send to the http.get method instead of just supplying the request.url.
var options = {
host: '<host part of url without the protocal prefix>',
path: '<path part of url>'
port: 80,
method: 'GET' }
I tested the following code on my local box and on AppFog and the IPs were different. Whatismyip returned my local interent ip address when running locally and on the AppFog hosted app it returned the AppFog server ip.
var port = process.env.VCAP_APP_PORT || 8080;
var http = require('http');
var options = {
host: "www.whatismyip.com",
port: 80,
path: '/',
method: 'GET'
};
http.createServer(function(request, response) {
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(d) {
response.write(d);
});
res.on('end', function() {
response.end();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
response.write("error");
response.end();
});
}).listen(port);

Difficulties with node.js proxy

I am attempting to make a GET request for a single image on another server from node.js.
var http = require('http');
var site = http.createClient(80, '192.168.111.190');
var proxy_request = site.request('/image.png');
proxy_request.on('response', function (proxy_response) {
console.log('receiving response');
proxy_response.on('data', function (chunk) {
});
proxy_response.on('end', function () {
console.log('done');
});
});
And even with this code, I can't get the "receiving response" message to print out. Outside of node, I can do a curl http://192.168.111.190/image.png just fine, but is there something else I might be missing?
for get requests try the http.get API http://nodejs.org/docs/v0.4.9/api/http.html#http.get
var http = require('http');
var options = {
host: '192.168.111.190',
port: 80,
path: '/image.png'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});

Resources