NodeJS/express: server became unresponsive after running for some time

Initially, my service using express and webpack ran smoothly. However, I started encountering an issue where the server would hang with no message code being received, as shown in the server message screenshot (server message screenshot). This problem kept recurring.

Below is my app.js code:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();
var mysql = require('mysql');

var generals = require('./routes/generals');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/generals', generals);
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// handle 404 errors
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

The route file generals.js:

var express = require('express');
var bodyParser = require('body-parser');

var router = express.Router();
var pool = require('./connections');

router.get('/dropDownValue/', function(req, res, next) {
    pool.getConnection(function(err, connection) {
        connection.query("select * from drop_down_value order by id desc", function(err, rows) {
            if (!err && rows.length > 0) {
                res.json(rows);
            } else {
                res.json([]);
            }
        });
    });
});
And the connections file:

var mysql = require('mysql');

var pool = mysql.createPool({
    host: 'xxx',
    user: 'xxx',
    password: 'xxx',
    database: 'xxx'
});

exports.getConnection = function (callback) {
    pool.getConnection(callback);
};

Answer №1

After utilizing pool.getConnection(), ensure to return the connection back to the pool once you have finished with it (after the query has been executed):

pool.getConnection(function(err, connection) {
    connection.query("select * from drop_down_value order by id desc", function(err, rows) {

        connection.release(); // <- this

        if (!err && rows.length > 0) {
            res.json(rows);
        } else {
            res.json([]);
        }
    });
});

If you fail to release the connections back to the pool after performing 10 queries, the pool will run out of available connections and start waiting indefinitely for connections to be released, causing requests to hang.

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

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Converting a 'Functional Component' to a 'Class Component' in React with Material-UI: A Step-by-Step Guide

Can anyone help me convert this Material-UI example into a Class Component? import React from 'react'; import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@mate ...

Discover the art of highlighting errors with React-hook-form and MUI React

My code consists of the following component: const App = () => { const formProps = useForm({ mode: "onBlur", }); const { handleSubmit, formState, register, watch, reset } = formProps; return ( <FormProvider {...formProps}> & ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Utilizing Redux in Conjunction with the useEffect Hook

I have come across a situation where mixing certain technologies has resulted in double re-rendering in my small use case. I read that theoretically it should be okay, but I'm facing issues. The problem occurs when redux dispatch is executed and some ...

Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with: <script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16. ...

Having trouble with my nodejs Express regex path. It works fine in my test environment but not in my actual code. Any suggestions on what

Looking for a simple filter in nodejs express routing path. The parameter must be either word1 or word2. Tested using: Using the expression: test/:gender(\b(word1|word2)\b) The path tested was: test/word2 Everything seems to work fine as "The ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

What is the process for extracting content from CSS comments or annotations in a stylesheet?

Here's an interesting concept: allowing users to define a set of CSS rules with annotations. For example: /* @name Page style */ body { font: 16px/1.5 Arial; /* @editable */ background-color: #fff; /* @editable */ } /* @name Section header */ ...

angular $stateProvider behaving unexpectedly with routing

Within my main file titled index.html, I have incorporated the following basic markup... <body ng-app="starter" ng-controller="AppCtrl"> <div ui-view></div> </body> In my separate file called app.js, I am utilizing $stateProvi ...

Having trouble connecting v-model to vue-date-picker

My experience with the vue-date-picker and v-model for two-way data binding has been interesting. Initially, I set the value to a date (referred as startDate in this case) and printed the passed value (i.e. startDate) in the console. The initial value pa ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

What triggers the @auth0/nextjs-auth0 package to call the /me API every time the route changes?

Recently, I integrated the auth0 SDK into my Next.js projects and overall it's been a smooth process. However, I've encountered a minor issue. Every time I change routes while logged in, the /me API is invoked. This leads to the user obtained thr ...

Adjusting the Z-index of the autocomplete dropdown and exploring the functionality of getOptionSelected

I'm currently working on integrating the Autocomplete material ui widget into my web application, but I'm facing an issue where the drop-down menu appears behind my edit panel. While I can still use my arrow keys to navigate and select options, i ...

"Creating a Hyperlink that Navigates to Specific Content Within a

I have a situation where I am trying to link to sections on the page contained within collapsed fieldsets. My goal is that when a user clicks on this link, the page should scroll down and automatically expand the fieldset to display the content inside. E ...

The React-Leaflet curly braces positioned on the top left corner of the map

Is there a way to remove the curly braces and symbols near the zoom pane when the map is too far? https://i.stack.imgur.com/eGQCd.png p.s. Here is some provided code for reference: p.s. 2 - I have noticed that adding a condition like {condition1 &a ...

Tips for managing, showcasing, and modifying checkbox controls within an AngularJS environment

I have successfully completed the saving part of the code. Below, I am demonstrating how I displayed the saved data and my attempts to edit the form upon clicking the edit button. Here is my AngularJS code: var module = angular.module('myApp&apos ...