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!




