The abrupt end of an HTTP connection occurs in a Node.js application deployed on Amazon EC2

I am currently running a REST API on Amazon EC2 using Node.js (Express).

During a specific REST call, the client receives a reply of approximately 5MB. However, before the client can fully receive the reply, an error message is displayed:

Premature end of Content-Length delimited message body

To investigate this issue further on the server-side, I implemented a connection listener in my Node.js server as shown below:

var app = express();

var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
server.on('connection', function (socket) {
    log.debug('SOCKET OPENED' + JSON.stringify(socket.address()));
    socket.setTimeout(300000);   //5 minute timeout
    socket.on('end', function () {
        log.debug('SOCKET END: other end of the socket sends a FIN packet');
    });

    socket.on('timeout', function () {
        log.warn('SOCKET TIMEOUT');
    });

    socket.on('error', function (error) {
        log.warn('SOCKET ERROR: ' + JSON.stringify(error));
    });

    socket.on('close', function (had_error) {
        log.debug('SOCKET CLOSED. IT WAS ERROR: ' + had_error);
    });
});

Upon investigation, it was observed that SOCKET TIMEOUT events were being logged in the backend. Even after increasing the socket timeout to 5 minutes, the issue persisted.

Interestingly, when the REST API was hosted on Google Compute Engine previously, this problem did not occur.

What do you think could be causing this issue?

Edit: Below is the code snippet for the REST API call: In my app.js, I have the following code:

require('./routes/index')(app);

The index.js file inside the routes directory looks like this:

var changeCase = require('change-case');
var express = require('express');
var routes = require('require-dir')();

module.exports = function (app) {
    Object.keys(routes).forEach(function (routeName) {
        var router = express.Router();
        require('./' + routeName)(router);
        app.use('/api/' + changeCase.paramCase(routeName), router);
    });
};

This script iterates through all the JavaScript files in the routes directory and registers the file names as URL paths in the app. Below is the code for the specific route where the issue occurs:

module.exports = function (router) {   
       router.get("/fetch", function (req, res, next) {
            itemModel.fetch(req.user.clientId, function (error, items) {
                if (error) {
                    res.status(500).json({error: error});
                } else {
                    res.json(items);    //items is a JSON array
                }
            });
        });
    }

Answer №1

By implementing a timeout for the HTTP server, we were able to successfully resolve the problem at hand.

const customServer = http.createServer(app);
const customPort = app.get('port');
customServer.listen(customPort);
customServer.setTimeout(300000, function (socket) {
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing minizinc npm in node.js - Exploring solution options without using the CLI interface

I have been utilizing the npm package found at https://www.npmjs.com/package/minizinc for my project. However, I noticed that the documentation doesn't provide clear instructions on how to input CLI strings/options in the model parameter to potentiall ...

Placing a middleware function before express.static causes difficulties

I have the latest version of express (4.1.1 as of now) installed. It comes with a built-in middleware for serving static files. The standard way to use this middleware is: app.use(express.static(path.join(__dirname, 'public'))); Everything wor ...

Unable to add key/value pair to object in Node

While using Node, I encountered a strange issue where I was unable to attach the key/value pair broadcastStamp = date to the object "result." Despite confirming that it is indeed an object with typeof, no errors were thrown - the key/value simply did not a ...

The directory "Users/node_modules/crypto-browserify" is not a valid directory in react

After discovering the package crypto-browserify on GitHub, I attempted to integrate it into my React Native project. Following the command npm install --save crypto-browserify, I then imported it using var crypto = require('crypto-browserify');. ...

The compatibility between Node.js and Git seems to be lacking

I'm attempting to set up automatic deployment with GitHub. I have created a JavaScript file to act as a "server" to receive the hook from GitHub, and that part is working flawlessly. However, I'm struggling with getting my hook.sh script to execu ...

Setting up NodeJS on Ubuntu 13.10

In the past, I have always compiled NodeJS from source. However, this time I decided to use the default apt repository for easier updates. Unfortunately, I'm having some trouble understanding what's happening. When I run the command: sudo ap ...

As I attempted to set up sb-admin-bs4-angular2-master, an application built with Node.js, I encountered an error message while running the npm install command

view image details here After running npm install -g ts-node, I proceeded with npm install only to encounter an error that left me clueless. Subsequently, when attempting npm start, a series of errors related to the gulp server or similar issues emerged. ...

Utilizing lodash to Filter Arrays Within Arrays

Let's take a look at the JSON structure provided below. comapany : ABC Emp Info:[ { empName: D, empID:4 salary[ { year: 2017, ...

Encountering difficulties with uploading upcoming project on a cpanel hosting due to an issue with the npm package

While attempting to upload my next project on a cpanel, I encountered an error during the installation of npm packages. npm ERR! code ERESOLVEnpm ERR! ERESOLVE unable to resolve dependency treenpm ERR! ERR! Found: <a href="/cdn-cgi/l/email-protection" c ...

Rearrange the positions of the latitude and longitude values in a JSON file without any additional tags

I have a JSON file with the following code snippet. I am looking to swap the latitude and longitude values while keeping the output the same. "path": [ [ -0.662301763628716, 51.48792441079866 ], [ ...

Encountering 404 Errors while Attempting to Reach API Endpoint in an Express.js Application Hosted on cPanel

I have a Node.js application running on cPanel, and I'm facing 404 errors when trying to access an API endpoint within my app. Let me provide you with the setup details: Directory Structure: public_html/ server.mjs index.html node_modules ...

Conduct comprehensive testing for secured routes within mongoDB integration

Running an integration test for one of the express routes in the application has been a challenge for me. This particular route is protected and allows users to create suppliers only when authenticated. I attempted to log in the user before making a requ ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

Issue with installing the latest React version alongside MUI version 5 on NodeJS 20.9.0: experiencing difficulty in compatibility

Encountering problem getting the latest mui version with the most recent react on node 20.9.0 These are the steps I took: Ran npx create-react-app my-project Navigated to my-project directory using cd command Installed @mui/material, @emotion/react, and ...

Does running npm install automatically compile the library code as well?

I have a query regarding npm and its functionality. I also posted the same question on Reddit, but haven't received a satisfying answer yet. Let's use the jQuery npm package as a case study. Upon running the command npm install jquery, I notic ...

Encountering a JSON error while attempting to install vue/cli using npm

After running npm i -g @vue/cli, I am seeing several warnings. How can I go about investigating and resolving this issue? npm WARN deprecated @hapi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3999c9ab3c2c6ddc2ddc2">[em ...

A Minor Mistake: Switching from 3 to 4 in Express. When relocating a controller and attempting to access index "Route.get(), make sure to include callback functions. Instead, an [object Undefined]

Dear all, I have encountered an error that seems to be unique to my situation. I am currently following the instructions from the Getting Mean book, but I am applying them to an Express 4 app instead of Express 3. In app.js app.set('views', pat ...

Test the file upload functionality of a Node Js application by simulating the process using Chai

My API testing involves receiving a file as input. I have successfully used the attach() function for this purpose. To cover all scenarios, I anticipate using around 20 different input files. Rather than storing these 20 files individually, my idea is to c ...

Error message 'Token not found' received after attempting to process payment through Stripe

I am in the process of setting up payment functionality using the Stripe API on an iPad. The goal is to allow users to log into their Stripe account and accept payments from others. To achieve this, I am utilizing Stripe Connect for authentication and savi ...