clients are unable to receive any data, resulting in HTTP 5XX errors. Below are the details of the problem and the steps I have taken to resolve it.

בנימין זיידנר 20 Reputation points
2024-09-30T10:19:54.6833333+00:00

I am encountering issues deploying my Node.js application to Azure App Service. While the server starts successfully and connects to the database, clients are unable to receive any data, resulting in HTTP 5XX errors. Below are the details of the problem and the steps I have taken to resolve it.

Server indicates it is running and connected to the database.

  1. Client requests result in HTTP 5XX errors with no data returned.
  2. No data is being sent from the server to the client despite successful handling of requests.
       node js
       server.jsHelprequire('dotenv').config();
       const express = require('express');
       const sql = require('mssql');
       const cors = require('cors');
       const path = require('path');
       const helmet = require('helmet');
       const appInsights = require("applicationinsights");
       // הגדרת Application Insights באמצעות משתנה הסביבה
       appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING)
           .setAutoDependencyCorrelation(true)
           .setAutoCollectRequests(true)
           .setAutoCollectPerformance(true)
           .setAutoCollectExceptions(true)
           .setAutoCollectDependencies(true)
           .setUseDiskRetryCaching(true)
           .start();
       // אתחול Express
       const app = express();
       const port = process.env.PORT || 3000;
       // הגדרת CORS
       app.use(cors({
         origin: "*",
         methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
         allowedHeaders: ["Content-Type", "Authorization"]
       }));
       // הוספת Helmet לאבטחה
       app.use(helmet());
       // הגדרת קבצים סטטיים
       app.use(express.static(path.join(__dirname, 'wwwroot')));
       // הגבלת גודל הבקשות
       app.use(express.json({ limit: '10kb' }));
       app.use(express.urlencoded({ limit: '10kb', extended: true }));
       // בדיקת משתני סביבה
       const requiredEnvVars = ['DB_HOST', 'DB_USER', 'DB_NAME', 'DB_PORT', 'DB_PASSWORD', 'APPLICATIONINSIGHTS_CONNECTION_STRING'];
       requiredEnvVars.forEach(varName => {
           if (!process.env[varName]) {
               console.error(`Missing required environment variable: ${varName}`);
               process.exit(1);
           }
       });
       // הגדרת פרטי החיבור למסד הנתונים
       const config = {
           user: process.env.DB_USER,
           password: process.env.DB_PASSWORD,
           server: process.env.DB_HOST,
           port: parseInt(process.env.DB_PORT) || 1433,
           database: process.env.DB_NAME,
           options: {
               encrypt: true,
               enableArithAbort: true
           }
       };
       // אתחול מאגר החיבורים הגלובלי
       const poolPromise = sql.connect(config)
           .then(pool => {
               console.log('Connected to the database successfully');
               return pool;
           })
           .catch(err => {
               console.error('Database Connection Failed! Bad Config: ', err);
               process.exit(1);
           });
       // הוספת לוגים לכל בקשה
       app.use((req, res, next) => {
           console.log(`${req.method} ${req.url}`);
           next();
       });
       // 
       app.get('/', (req, res) => {
           res.sendFile(path.join(__dirname, 'wwwroot', 'index.html'));
       });
       // דוגמה לראוט API
       app.get('/api/users', async (req, res, next) => {
           try {
               const pool = await poolPromise;
               const result = await pool.request().query('SELECT * FROM Users');
               res.json(result.recordset);
           } catch (error) {
               next(error); // העברת השגיאה ל-middleware לטיפול בשגיאות
           }
       });
       // Middleware 
       if (process.env.NODE_ENV === 'development') {
           app.use((err, req, res, next) => {
               console.error(err.stack);
               res.status(500).json({ error: err.message, stack: err.stack });
           });
       } else {
           app.use((err, req, res, next) => {
               console.error(err.stack);
               res.status(500).json({ error: 'Internal Server Error' });
           });
       }
       // 
       const server = app.listen(port, () => {
           console.log(`Server is running on port ${port}`);
       });
       // 
       process.on('SIGTERM', () => {
           console.log('SIGTERM signal received: closing HTTP server');
           server.close(() => {
               console.log('HTTP server closed');
               sql.close();
           });
       });
       
    
       node js 
       
       <?xml version="1.0" encoding="utf-8"?>
       <configuration>
         <system.webServer>
           <handlers>
             <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
           </handlers>
           <rewrite>
             <rules>
               <!-- ניתוב כל שאר הבקשות לשרת Node.js -->
               <rule name="DynamicContent" stopProcessing="true">
                 <match url=".*" />
                 <conditions>
                   <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                 </conditions>
                 <action type="Rewrite" url="server.js" />
               </rule>
             </rules>
           </rewrite>
           <security>
             <requestFiltering>
               <hiddenSegments>
                 <add segment="node_modules"/>
               </hiddenSegments>
             </requestFiltering>
           </security>
           <httpErrors existingResponse="PassThrough" />
           <staticContent>
             <mimeMap fileExtension=".json" mimeType="application/json" />
             <mimeMap fileExtension=".css" mimeType="text/css" />
             <mimeMap fileExtension=".js" mimeType="application/javascript" />
             <!-- הוסף סיומות נוספות לפי הצורך -->
           </staticContent>
           <iisnode
             watchedFiles="*.js;iisnode.yml"
             loggingEnabled="true"
           />
         </system.webServer>
       </configuration>
       
    
       {
         "name": "wevote-app",
         "version": "1.0.0",
         "description": "wevote",
         "main": "server.js",
         "scripts": {
           "start": "node server.js"
         },
         "dependencies": {
           "applicationinsights": "^3.3.0",
           "bcryptjs": "^2.4.3",
           "cors": "^2.8.5",
           "dotenv": "^16.4.5",
           "express": "^4.21.0",
           "helmet": "^6.2.0",
           "jsonwebtoken": "^9.0.2",
           "moment-timezone": "^0.5.45",
           "morgan": "^1.10.0",
           "mssql": "^11.0.1",
           "nodemailer": "^6.9.15",
           "xlsx": "^0.18.5"
         },
         "engines": {
           "node": ">=14.0.0"
         }
       }
       
    
Azure SQL Database
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
982 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Sai Raghunadh M 310 Reputation points Microsoft Vendor
    2024-09-30T19:27:34.88+00:00

    Hi @ בנימין זיידנר,

    Thanks for the question and using MS Q&A platform.

    I understand that you are encountering 5XX errors when deploying your Node.js application to Azure App Service. These errors can arise for several reasons. Here are some steps and suggestions to help you diagnose and potentially resolve the issue:

    1.) Improve your logging to get more details about requests and responses. For example, you could log the response status code and any errors that happen during request processing. You can change your API route like this:

    app.get('/api/users', async (req, res, next) => {
        try {
            const pool = await poolPromise;
            const result = await pool.request().query('SELECT * FROM Users');
            console.log('Fetched users:', result.recordset);
            res.json(result.recordset);
        } catch (error) {
            console.error('Error fetching users:', error);
            next(error);
        }
    });
    

    2.) Ensure that your Azure App Service can connect to your SQL database. Check that:

    • The connection string in your environment variables is correct.
    • Your database is set to allow connections from Azure services.
    • Any firewall rules are correctly set up.

    3.) Double-check that all required environment variables are correctly set in the Azure App Service, as deployments may sometimes fail to recognize them.

    4.) Also, ensure that your error-handling middleware is defined properly and is capable of catching all potential errors:

    app.use((err, req, res, next) => {
        console.error('Error middleware:', err);
        const statusCode = err.status || 500;
        res.status(statusCode).json({
            error: statusCode === 500 ? 'Internal Server Error' : err.message,
        });
    });
    

    5.) Sometimes, the default timeout settings may not be sufficient, especially for database calls. Consider increasing the timeout settings for the database connection.

    6.) If possible, try to replicate the production environment locally, including the environment variables, and see if you encounter the same issues. This can help determine whether the problem is with the code or the Azure environment.

    7.) Test your API endpoints using tools like Postman or cURL to confirm that the issue isn’t related to the client-side code or request format.

    8.) Ensure that your middleware, such as error handling, is set up correctly and in the appropriate order, particularly concerning routes and static files.

    9.) While you’ve configured CORS, make sure that requests from the client are allowed, and check the console for any CORS-related errors.

    By following these steps, you should gain greater insight into the issues your application is experiencing and hopefully resolve the HTTP 5XX errors.

    If this answers your query, do click Accept Answer and Yes for was this answer helpful. And, if you have any further query do let us know.

    0 comments No comments

  2. בנימין זיידנר 20 Reputation points
    2024-09-30T22:52:40.81+00:00

    Thank you very much for the detailed response. However, I am still unable to retrieve data on the client side. Although I have successfully established a connection to the database, the data does not load on the client. Additionally, I have created an API and received responses in Kudu."

    C:\home\site>curl -X GET https://wevote-b8eqa2gwbubcbwf0.canadacentral-01.azurewebsites.net/api/users

    The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

    C:\home\site>C:\home\site>

    % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 103 100 103 0 0 648 0 --:--:-- --:--:-- --:--:-- 686

    I would greatly appreciate your help, thank you

    \home\site>node server.js AppInsightsAgent: Successfully loaded ETW AppInsightsAgent ETWLogger Application Insights SDK already exists. Module is already installed in this application; not re-attaching. Installed SDK location: C:\home\site\node_modules\applicationinsights\out\src\index.js @azure/opentelemetry-instrumentation-azure-sdk [   'Module @azure/core-tracing has been loaded before @azure/opentelemetry-instrumentation-azure-sdk so it might not work, please initialize it before requiring @azure/core-tracing' ] The 'logRecordProcessor' option is deprecated. Please (x86)\\SiteExtensions\\JavaApplicationInsightsAgent\\3.5.1\\java\\applicationinsights-agent-co
    deless.jar'" } Server is running on port 3000 Connected to the database successfully 
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.