0

I'm trying to get a Static Web App to communicate with a SQL Database via an HTTP Trigger in an Azure Function App.

When I try to submit the form on the website, I get a 500 Internal Server Error. Here’s the error from the browser console:

----------
POST
script.js:14
https://totallyfunfunctionapp.azurewebsites.net/api/HttpTrigger1?
net::ERR_ABORTED 500 (Internal Server Error)
(anonymous) @ script.js:14
----------
script.js:36
Error: Error: Network response was not ok Internal Server Error
at script.js:23:19
----------

The front-end code is hosted on GitHub and deployed to Azure.

The web app is simple: a single line text input with a submit button. My goal is to store the entered text in the SQL Database.

Here's the front-end JavaScript I'm using:

document.getElementById('submitButton').addEventListener('click', function() {
    var textInput = document.getElementById('textInput').value;
    var result = document.getElementById('result');

    // URL of your Azure Function
    const functionUrl = 'https://totallyfunfunctionapp.azurewebsites.net/api/HttpTrigger1?';

    // Create the request body
    const requestBody = {
        textInput: textInput
    };

    // Make the request to your Azure Function
    fetch(functionUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.text(); // Use text() to handle non-JSON responses
    })
    .then(text => {
        try {
            const data = JSON.parse(text); // Parse the text response as JSON
            result.textContent = 'Data received: ' + JSON.stringify(data);
        } catch (error) {
            result.textContent = 'Error parsing JSON: ' + error.message;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        result.textContent = 'Error: ' + error.message;
    });
});

And here's the code for the Function App HTTP Trigger:

const sql = require('mssql');

const config = {
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    server: process.env.DB_SERVER,
    database: process.env.DB_NAME,
    options: {
        encrypt: true,
        trustServerCertificate: false
    }
};

module.exports = async function (context, req) {
    context.log('Function execution started');
    
    try {
        await sql.connect(config);
        const result = await sql.query`SELECT * FROM Entries`;

        context.res = {
            status: 200,
            body: result.recordset.length > 0 ? result.recordset : { message: 'No data found' },
            headers: {
                'Content-Type': 'application/json'
            }
        };

    } catch (err) {
        context.log.error('Error encountered:', err);

        context.res = {
            status: 500,
            body: JSON.stringify({ error: `Error connecting to database: ${err.message}` }),
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }
};

I've added the Function App's possible outbound IP addresses to the database's firewall rules.

I’m new to integrating Azure Functions with databases and have tried searching for solutions but haven’t had any luck. Any guidance or resources on what might be going wrong would be greatly appreciated!

1 Answer 1

0

Regarding the error POST 500 (Internal Server Error), you should check the server logs or console log in the browser. While trying your code, I encountered a CORS error as shown in the image below:

errror Output

To resolve this, add the following to your local settings file local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "FUNCTIONS_WORKER_RUNTIME": "node"
  },
  "Host": {
      "CORS": "*"
  }
}

Additionally, add the CORS settings for all URLs mentioned for above image in the CORS tab of your function app in Azure:

Cors In Azure

Make sure to place index.html in the src folder.

I referred to this MSDOC to build a static site with Azure Static Web Apps using no framework:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="Hello.css">
    <title>Submit Form</title>
</head>

<body>
    <main>
        <h1>Submit Form</h1>
        <input type="text" id="textInput" placeholder="Enter text">
        <button id="submitButton">Submit</button>
        <p id="result"></p>
    </main>

    <script src="script.js"></script>
</body>

</html>

Refer to this MSDOC for Azure Static Web Apps CLI Configuration.

Local Output:

Local Output

Yml file with Out API :

app_location: "./src" 
 api_location: ""
 output_location: "." 

I referred to this MSDOC to add an API to Azure Static Web Apps with Azure Functions using no framework.

Yml file with API Localtion :

app_location: "./src" 
 api_location: "./api"
 output_location: "." 

Refer to this SO for YAML workflow configuration in Static Web App.

Azure Static Web App Output:

Azure Static Web App Output

Azure SQl Data Sample Table View :

Azure SQl Data Sample Table View

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.