Node.js Socket hang up error - node.js

When using http.createServer with node.js , I get the following error:
events.js:48
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1092:15)
at Socket.onend (http.js:1155:27)
at TCP.onread (net.js:349:26)
simple code :
http.createServer(
connect_cache({rules: [{regex: /.*/, ttl: 60000}]}),
function(b_request, b_response){ ..... }
);
so , what does error mean ? and how can i fix it ?
thank !

http.createServer() expects at most a single function as its argument, which is then set as the handler for the request event. connect_cache() doesn't have the correct signature to be a handler. Presumably it's written as middleware to be used under Connect or something (like Express) built on it, but you can't pass Connect middleware directly to an instance of http.Server; you need to create a Connect object, pass the middlware to it, and then pass the Connect object to http.createServer().

Related

why is my node.js app crashing after write after end error

So I'm trying go through a 8 hours video tutorial on Node.js and Express but I seem to hit a point where I am not understanding well.
There's a quick example of an app running but my app keeps crashing unlike in the videos that seems to be working fine. The app code is below and my dilemma is after as well as the error message on console.
const http = require('http')
const server = http.createServer((req,res)=> {
if(req.url === '/'){
res.end('Welcome to our home page')
}
if(req.url === '/about'){
res.end('Here is our short history')
}
res.end(`
<h1>Oops!</h1>
<p>We can't seem to find the pages you are looking for</p>
Back Home
`)
})
server.listen(5000)
whenever I start the app in my terminal it starts fine. My problem is that when I go to the browser at localhost:5000/, localhost:5000/about my app crashes. If I go to localhost:5000/error* it working fine until I click the link that send me to localhost:5000/ and then crashes again. With the following messages.
node:events:504
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:371:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (/home/chachoz007/NodeJS/tutorial/app.js:12:6)
at Server.emit (node:events:526:28)
at parserOnIncoming (node:_http_server:951:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Now I get that my app crashes because res.end and the end is trying to write after it already ended in one of the if statements from before.
My problem is why it is crashing compared to the tutorial that i am following that is not crashing. My version of node.js is 16.**** compared to the tutorials version of 14.****
i was wondering if someone could give me some intell on this issue.
You can only call .end() once for each request.
Your code executes the .end() method twice whenever the request is for / or /about; once in the if-else and then a second time after that. One way to solve it is to use "else if" and then else for the final .end() call.

Node.js proxy server socket hang up

I am using Node.js as a proxy server and I cannot get rid of the following error. Can anyone familiar with NodeJS assist in finding a solution. Each time this happens I have to restart the .js proxy.
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1264:15)
at CleartextStream.socketCloseListener (http.js:1315:23)
at CleartextStream.EventEmitter.emit (events.js:93:17)
at SecurePair.destroy (tls.js:938:22)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
Thanks in advance for any assistance.
This error happens sometimes, it's normal, because client/server can break connection by himself in a wrong way. You could listen for 'error' event on socket, so you can catch error and don't restart whole process.
So in my case the socket hangup was with the post request and the get request worked fine from post man and as well as from browser
The post request body which were sent from 1st server was the raw JSON, so the proxied server will not be able to parse the body.
We need to stringify the body on request, below code will help us to stringify and send the data to proxy server on trigger of request
const proxy = httpProxy.createProxyServer();
proxy.on('proxyReq', proxyRequestHandeler);
proxyRequestHandeler = (proxyReq, req) => {
if(req.body) {
const bodyData = JSON.stringify(req.body);
// In case if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// Stream the content
proxyReq.write(bodyData);
}
}

Exception in Node server that uses http module

Please note that the above "possible answer" questions does not contain an answer to my question. I am using require("http"). In that question the person is taking a socket input variable that they can put a handler on. I do not have the same variable.
I have a very simple server that I have written in Node.
var http = require("http");
var sys = require("sys");
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
target: "someServer"
});
http.createServer(function(request, response) {
try {
proxy.web(request,response);
} catch (err) {
sys.puts("I caught an error!");
}
}).listen(5000);
When I leave my app running, it crashes. My command line says:
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:900:11)
at TCP.onread (net.js:555:19)
It seems to crash not when server is serving files, but when it is waiting for a long time between requests.
While my code is a little more complex, I do have error catching on every callback.
Why is it crashing? What can I do?
In node, sprinkling try and catch everywhere is not the same as catching every error. (And in most cases, doing so is useless.) Asynchronous operations cannot throw useful exceptions because control long ago left the block of code that invoked the operation.
Instead, many objects emit an error event. The error event is a special case in that node will throw a "real" exception if there are no listeners for the event. Because this exception is thrown from code you do not and cannot control (ie wrap with try/catch), it goes uncaught and the process ends.
So if you do not add an error listener to sockets, a socket error will bring down the entire app.
However, your unhandled error is not coming from your http requests. The http module adds an error handler to every socket automatically, and re-emits the error as a clientError event on the Server. Because EventEmitters only throw when the event is named error, the fact that you don't handle clientError does not matter.
If we read http-proxy's documentation, we see that it also throws an error event, and you aren't listening for it. Thus, your app dies whenever there's an error fetching something from an upstream server.
Add an error handler.
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong.');
console.error(err);
});
Any time you see this error ("// Unhandled 'error' event"), it means you need to find out what is emitting an error event and add a listener to handle the error.

Debugging stray uncaught exceptions (ECONNRESET) in a node cluster

In my node.js app which uses the cluster module, I'm intermittently seeing errors like this:
events.js:71
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:863:11)
at TCP.onread (net.js:524:19)
This brings down my whole app, and so far the only way I've been able to deal with these is by binding a process.on('uncaughtException'). I'd like to figure out the underlying cause, but the above stack trace is pretty useless.
Is there some way to figure out what's causing these exceptions?
I should note that I'm seeing these only in the cluster master, not the workers, which leads me to suspect that they have something to do with the way the cluster modules does its magic in distributing connections to workers.
This answer was helpful: https://stackoverflow.com/a/11542134/233370
Basically, I installed longjohn and was then able to get the full async stack trace to figure out the underlying cause (rabbit.js in my case).
It seems that express enabled keep-alive by default.
In order to close connection after response you can add
res.set("Connection", "close");
Alternatively you can add a middleware in your app to close connection after each response:
app.use(function(req, res, next) {
res.set("Connection", "close");
next();
});

Nodejs error while trying to access sharepoint

I get the following error while trying to access SharePoint from nodejs
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:769:11)
at Object.afterConnect [as oncomplete] (net.js:760:19)
below is the code
var SP = require('sharepoint'),
site = //url,
username = //username,
password = //password;
var client = new SP.RestService(site),
contacts = client.list('Contacts');
var showResponse = function (err, data) {
console.log(data);
}
client.signin(username, password, function () {
// At this point, authentication is complete,
// so we can do requests.
// Example request: Get list items
// showResponse is used as callback function
contacts.get(showResponse)
});
The important part of that error message is ECONNREFUSED, meaning the connection was refused right away. That means it never got to the point of checking your username and password or anything.
You should double-check your value for site. Maybe the server is running on a different port or you have a typo in that value.
Depending on the SharePoint module implementation you've to pass the entire url addressing the REST service.
In SharePoint 2010 the entire REST Service url should look like this
http:// %%SharePointSiteUrl%% /_vti_bin/ListData.svc
You should double check the outgoing requests direction SharePoint by using fiddler or an alternative HTTP watcher.

Resources