I am trying to create a simple server and a simple client with node.js using http module. Server is working fine but client is not. Please help me to find the bug...
Server Is :
var server = require('http').createServer();
server.on('request', function(req, res){
res.end("hello, world");
});
server.listen(4000);
Client Is :
var options = {
host : 'localhost',
port : 4000,
method : 'GET',
path " '/'
};
require('http').request(options, function(res){
console.log(require('util').inspect(res));
res.on('data', function(data){
console.log(data);
});
I am running them in different terminal windows as node server.js & node client.js.
I am getting below mentioned error on the client.js running terminal after around 10 mins.
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1473:15)
at Socket.socketOnEnd [as onend] (http.js:1569:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Thanks !
The request() method of the HTTP library will not automatically end requests, therefore they stay open, and time out. Instead, you should either end the request using req.end(), or use the get() method, which will do so automatically.
var http = require('http');
var req = http.request(options, function(res) {
// handle the resposne
});
req.end();
Or:
http.get(options, function(res) {
// handle the resposne
});
Related
I have this simple server to play around express and node. I am getting this error when I call a function inside the app.get() method. I have serached around the internet and still I couldn't figure it out what's going in here.
Error
http_outgoing.js:518
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after
they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at Array.write (G:\Project\Node Projects\Automater\node_modules\finalhandler\index.js:285:9)
at listener (G:\Project\Node Projects\Automater\node_modules\on-finished\index.js:169:15)
at onFinish (G:\Project\Node Projects\Automater\node_modules\on-finished\index.js:100:5)
at callback (G:\Project\Node Projects\Automater\node_modules\ee-first\index.js:55:10)
at IncomingMessage.onevent (G:\Project\Node Projects\Automater\node_modules\ee-first\index.js:93:5)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Here is my code
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/user',(req,res,next) =>{
log(req,res,next);
res.send('user');
})
app.get('/',(req,res,next) => {
res.send('Success');
});
function log(req,res,next){
console.log('Logger !!!');
next();
}
app.listen(port, () => console.log(`listening on port ${port}!`));
You should remove res.end() because res.send(...) calls res.write, res.setHeaders, and res.end for you. When you call res.send(...) you already send response to client.
It means that the response has already been sent to the client.
You are doing 2 things: res.send('user'); res.end();
Remove res.end() and it should be good.
i have this code in express.
var express = require('express');
var http = require("http");
var https = require("https");
var app = express();
var optionsSB = {
host: 'domain.com',
path: '/wp-content/themes/domain/includes/ajax/get_properties.php'
};
var optionsLV = {
host: 'apiproperties.local',
path: '/properties/storeSB',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
https.get(optionsSB, function (https_res) {
var dataSB = "";
https_res.on("data", function (chunkSB) {
dataSB += chunkSB;
});
https_res.on("end", function () {
http.request(optionsLV, function(http_res){
var dataVL = "";
http_res.on("data", function (chunkVL) {
dataVL += chunkVL;
});
http_res.on("end", function () {
console.log(dataVL);
});
});
});
});
app.listen(3000, function () {});
I get this error
events.js:183
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:80
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
I already try some things but i dont know what is the problem, regards.
I follow some instruction from a tutorials and all works fine but that error i dont understand.
It will throw like this when you are getting an error in setting up the request with your https.get(), but you don't have any error handler to capture the error. You can supply an error handler:
https.get(...).on('error', function(err) {
// error here
console.log(err);
});
It appears that the specific error is ECONNREFUSED. It could be that the destination is not accepting your https connection or it could be that it doesn't like the way you were passing the options. Since all you have is a host and path, you can also just use the URL:
https.get("https://somedomain.com//wp-content/themes/domain/includes/ajax/get_properties.php", ...);
I'm trying to use named pipes in my application. The problem is when I try to connect to the named pipe before the server is running, I get the following error:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ENOENT \\?\pipe\\testpipe
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)
How can I check if the pipe exists before attempting to connect to it?
Note: Wrapping my connect code in a try-catch doesn't prevent the error.
Here is my code:
var net = require('net');
var addr = '\\\\?\\pipe\\testpipe';
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
Using the domain module prevents a fatal error. The following code can be used to safely run the connect code.
Not what I was hoping for, but the closed solution since there have been no answers.
var net = require('net');
var domain = require('domain');
var addr = '\\\\?\\pipe\\testpipe';
var d = domain.create();
d.on('error', function(err) {
console.error(err);
});
d.run(function() {
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
});
make the socket, then listen for an error event, then call connect and it won't be thrown: https://nodejs.org/api/net.html#net_event_error_1
I'm as new to Node and when I trying to run my first ever simple node app that makes an http connection to www.google.com host. While I tried some of the solutions suggested on prior threads nothing really seemed to help. While the below error is not a rare case but need someone to advise me what's missing from my setup/env.
source code - test.js - as simple as below -
var http = require('http');
var options = { host: 'www.google.com'};
http.get(options, function(err, res) {
console.log("GOT ERR?", err);
console.log("GOT RES?", res);});
I get the below error.
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)
Your callback is wrong. Try to write your code as follow:
var http = require('http');
var options = { host: 'www.google.com'};
// notice that the callback only receives a res parameter
// errors are handled on an event below
var req = http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
});
// handle errors
req.on('error', function(e) {
console.log("Got error: " + e.message);
});
Here is the documentation for http.get: http://nodejs.org/api/http.html#http_http_get_options_callback
The error that you are seeing (throw er; // Unhandled 'error' event) is because you do not have an even handler for the error event. Notice the req.on('error') in my code to address this.
I am new in NodeJS, and I am working an an example:
function test(req,res){
var path = urls[Math.floor(Math.random()*urls.length)];
console.log("try to redirect to:"+path);
http.get(path,function(res_server){
//how to send the data from res_server to res
});
}
And the urls is an array of url.
I wonder how can I send the data from the res_server to the original client response?
BTW, the url maybe http or https.
update
var urls=["url1","url2","url3"];
var path = urls[Math.floor(Math.random()*urls.length)]; // find an random item from the array
update:2
Fine, this is the complete simple test script:
var http=require("http");
http.createServer(function(req, res1) {
var url = 'http://www.google.com.hk/images/srpr/logo11w.png';
var hp=require("http");
hp.get(url, function(res2) {
res2.pipe(res1);
});
}).listen(3000);
It works, but if you change http://www.google.com.hk/...logo..png to https:/www.google.....png
It will throw error:
http.js:1840
throw new Error('Protocol:' + options.protocol + ' not supported.');
^
Error: Protocol:https: not supported.
at Object.exports.request (http.js:1840:11)
at Object.exports.get (http.js:1847:21)
at Server.<anonymous> (C:\Users\maven\Desktop\t.js:6:6)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2108:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at Socket.socket.ondata (http.js:1966:22)
at TCP.onread (net.js:525:27)
Change var http = require('http'); to var http = require('https');
I do not fully understand your example. Looks strange to me. However best would be to pipe the request response into the server response:
http.createServer(function(req, res1) {
var path = url.format({
protocol: 'http:',
host: 'www.google.com'
});
http.get(path, function(res2) {
res2.pipe(res1);
});
}).listen(3000);