Timeout when making an HTTP request

One question I have is regarding socket timeout in NodeJs.

To address the issue, initially, I included the following code :

    req.socket.once('timeout', function(err) {
        imports.logger.warn('Express socket timeout.', err);
        res.status(504).end('Connection timeout');
    });

However, I continued to encounter Express Socket timeout errors being logged in the console long after the page had loaded. To aid in debugging, I decided to add this line :

    req.socket.setTimeout(4000);

Surprisingly, all my requests were now handling an Express socket timeout after 4 seconds. Despite finding various information online, I am still struggling to fully grasp the concept.

My confusion lies in why the res.json() function, which closes the request, does not also close the socket. Could there be a connection with keep-alive or web sockets?

If the link pertains to web sockets, what would be the recommended practice? Should I manually close the socket and if so, where exactly should this be done?

If needed, you can refer to my simple Express route code below:

 app.get(apiUrl + '/:id', function (req, res) {

    NewsFeed.findById(req.params.id, function (err, newsFeed) {

        if (err) {
            return app.error(res, 404, 'Error 404: No news found');
        }

        res.json(formatNewsFeed(newsFeed));

    });

});

Answer №1

When it comes to HTTP, there is no strict rule that each request must have its own socket for communication. Instead, both the browser and server can keep a socket open even after a request is completed, allowing it to be used again for future requests. This practice is known as HTTP Keep-Alive. By reusing existing sockets, the process becomes faster as opening new ones can take time. As a developer, you typically do not need to concern yourself with managing individual sockets and can focus on working with the request object.

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

Integrating Express into a React Webpack project

I am currently in the process of integrating express into my React project to establish connections with databases for storing form data. As of now, I am using webpack to create a dev server that displays my React view. My technology stack includes... Web ...

What is the best way to utilize a deprecated npm package in a meteor application?

I have a package.js file where I currently depend on fluent-ffmpeg like this: Npm.depends({ "fluent-ffmpeg": "1.5.2", }); However, I now require the latest version of that library from the master branch in order to access a bug fix that hasn't bee ...

To retrieve a CSV file on the frontend, simply click a button in an AngularJS application that communicates with NodeJS and ExpressJS

How can I download a .csv file from the frontend? This is the code I am currently using: $http.get('/entity/consultations/_/registerationReport' ) .success(function (data) { myWindow = window.open('../entity/consultations/_/r ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...

Is it possible to create communication between Django, Tornado, and websockets?

Recently, I came across the recommendation to use Tornado along with Django for implementing websockets. I understand the reasoning behind this choice. However, let's consider a scenario where I want to send out notifications via the websocket server ...

Utilize an asynchronous method to upload files to Google Cloud Storage in a loop

I am new to using Javascript and have been working on a loop to upload images to Google Cloud Storage. While the image uploads correctly with this code, I'm facing an issue where the path (URL) is not being saved in the database AFTER the upload. I a ...

The deployment of a Create React app on Heroku encountered an issue due to the

Attempting to deploy my React application to Heroku with stack 22 has proven to be a challenge. The code works perfectly fine on my local machine, where I have both a Reactjs FrontEnd and Nodejs Backend set up. After completing the project, I integrated my ...

Can NPM Dependencies Be Stored in a Folder Inside a Git Repository?

Is there a way for NPM to install dependencies using a Git URL that points to a specific sub-folder within the repository? I searched through the documentation but couldn't find a clear answer. I am aware of how to set up a Git repository to act as a ...

Experiencing a persistent memory usage issue in Express / Node.js even after usage

While monitoring the memory usage of my website, I noticed that every request sent to the express server increases the memory usage by 0.5 MB and it does not decrease afterwards. Should I be concerned about this pattern? Does this indicate a memory lea ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

Using `req.body` to retrieve form data in express.js is not permitted

I have a form on my website that collects user data using input and selection fields. I'm looking to use an AJAX call triggered by the submit button's handler to save this data on the server. Below is an outline of the code: Client side: xhr.o ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

In JavaScript, merging objects will exclusively result in an identifier being returned

When working with mongoose, I have encountered an issue where combining data from multiple finds only displays the id instead of the entire object. Interestingly, when I use console.log() on the object directly, it shows all the contents. Below are snippe ...

Unable to locate 'URL' in the redux-auth-wrapper

Upon attempting to activate my ReactJS project using the npm start command, I encountered the following error message: ERROR in ./node_modules/redux-auth-wrapper/history4/locationHelper.js 17:11-25 Module not found: Error: Can't resolve 'url ...

Despite a clean Node console, I am facing difficulty in retrieving data by Id in my MERN stack application

I'm facing difficulty identifying the issue as I'm not receiving any error messages, although my route/controller isn't functioning with a specific id. Here is my controller: module.exports = getUserById = (req, res) => { User.findBy ...

Error message encountered in node-schedule: Unable to read undefined property upon job restart

Using node-schedule, I have successfully scheduled jobs on my node server by pushing them into an array like this: jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url))); Everything is working as expected. When the designated date ...

Could updating a CLI through npm be a viable solution?

Currently, I am developing a command line interface for nodejs. My plan is to distribute it via npm. I find the automatic update feature in Chrome and Firefox very appealing. I am considering running the following code on startup or just before the progra ...

Creating a setup in TypeScript to enable imports between CommonJS and ES modules (for node-fetch and Express)

I'm facing a challenge in trying to integrate two libraries into a single project: fetch-node, an ES module, and Express, which follows the CommonJS format. The issue arises from needing to import fetch-node using: import fetch from 'node-fetch&a ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...

Difficulty with routing stylesheets in my Node Express server

Currently, I am setting up the back-end structure for my website. The file setup looks like this: public css main.css main_b.css index.hbs index_b.hbs server server.js To reference style sheets in the index files, I use link attributes wit ...