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.
983 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Sai Raghunadh M 555 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.


  2. brtrach-MSFT 16,356 Reputation points Microsoft Employee
    2024-10-07T03:36:10.4166667+00:00

    @בנימין זיידנר I wanted to reach out to help assist Sai on this matter.

    Can you please check the application logs where your API is hosted? We want to see if we can locate the 500 errors and understand exactly what the http error and http_substatus is. You can access this application logs via the Azure portal or via KUDU. Knowing if this is a 502.64 or 502.131 can help us better narrow down the root cause in some cases.

    Next, can you please ensure that your environment variables are set correctly?

    Since your app works locally but not in Azure, we also want to check the connection string.

    Server=tcp:myserver.database.windows.net,1433;Database=myDataBase;User ID=mylogin@myserver;Password=myPassword;Trusted_Connection=False;Encrypt=True;
    

    Above is the standard connection string used for Azure SQL Database.

    Can you also see if your database server is accessible from your Azure App Service? And also ensure that your firewall settings on your SQL database allow for connections from your App Service (ensure that the outbound IP addresses for your App Service are allowed).

    Since you're using CORS, that could be another point of conflict. Make sure your CORS settings are correctly configured to allow requests from your client application. You have set origin: "*", which should allow all origins, but double-check if there are any additional restrictions or configurations needed.

    Lastly, the error message from the curl command suggests that the /api/users endpoint might not be available. Ensure that:

    • The route is correctly defined and accessible.
    • There are no typos in the URL.
    • The server is correctly handling the request and returning the expected data.

    Let us know the outcome of the above, including the HTTP error and substatus code, and if the other troubleshooting steps brought any relief. Otherwise, we can continue forward troubleshooting with the error code.

    0 comments No comments

  3. בנימין זיידנר 20 Reputation points
    2024-10-07T06:12:11.07+00:00

    In fact, I was not successful with the previous deployment. What I did was switch users and redeploy the code. First, I connected Visual Studio Code to the database structure in SQL Server. After that, I redeployed the code, and I was finally able to view the pages. Thank you for your prompt response, although it didn't quite help me solve the issue.

    Best regards, Binyamin.

    0 comments No comments

  4. בנימין זיידנר 20 Reputation points
    2024-10-07T08:01:07.76+00:00

    In fact, I was not successful with the previous deployment. What I did was switch users and redeploy the code. First, I connected Visual Studio Code to the database structure in SQL Server. After that, I redeployed the code, and I was finally able to view the pages. Thank you for your prompt response, although it didn't quite help me solve the issue.

    Best regards,

    Binyamin.

    0 comments No comments

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.