I’ve created an API using an Azure Function with NodeJS. It contains an HTML frontend where users can upload or download files from Azure Storage containers using SAS tokens. One of my new requirements is that the SAS tokens should be generated in the Azure Function itself, so I now have a function that generates SAS tokens. The issue with this is that I am not sure how to pass the generated token from my Azure Function to the HTML frontend. How would I do this?
I’ve tried inserting the SAS token function into my HTML script section, however it is not working because my code fails when trying to import packages to the HTML file. I’ve also tried calling the SAS token function from the Azure Function to my HTML, but that did not work either.
Edit: Adding code for more clarity.
HTML (index.html):
<script type="text/javascript" src="./index.js"></script><input type="button" onclick="createContainerSas()" value="run external javascript">
Javascript (index.js):
function createContainerSas(){
const accountName = "myaccountname";
const containerName = "mycontainername";
const accountkey = "myaccountkey";
const credential = new StorageSharedKeyCredential(accountName, accountkey);
const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net`, credential);
const containerClient = blobServiceClient.getContainerClient(containerName);
const sasOptions = {
containerName,
protocol: SASProtocol.HttpsAndHttp
};
sasOptions.permissions = ContainerSASPermissions.parse('cw'); // for creating and writing.
sasOptions.expiresOn = new Date(new Date().valueOf() + 3600*1000);
const sasToken = generateBlobSASQueryParameters(sasOptions, credential).toString();
return sasToken;
}
Two errors are returned – "Failed to load resource: the server responded with a status of 404 (Not Found)" and "Uncaught ReferenceError: createContainerSas is not defined"
2
Answers
With the below Node js Azure functions code, I can able to generate SAS token of a storage account.
Code:
Output:
With the above URL, I got the SAS token output at browser as below,
In your HTML file, you can use fetch() function to send a HTTP request to your Azure Function and get the SAS token.
Remember to replace ‘https://your-function-app.azurewebsites.net/api/your-function-name’ with the actual URL of your Azure Function.