0
votes

I'm trying to upload a file for the azure storage emulator in a react application.

I'm using https://aka.ms/downloadazurestoragejs

This is my code:

const azure = require('./azure-storage.blob.js');
const devStoreCreds = azure.generateDevelopmentStorageCredentials();
let blobService = azure.createBlobService(devStoreCreds);
const serviceProperties = {
    Cors: {
        CorsRule: [{
            AllowedOrigins: ['*'],
            AllowedMethods: ['POST', 'PUT'],
            AllowedHeaders: ['*'],
            ExposedHeaders: ['*'],
            MaxAgeInSeconds: 200
        }]
    }
};
blobService.setServiceProperties(serviceProperties, function(error, result, 
response) {
    if (error) {
        alert('service failed, open browser console for more detailed 
info.');
    }
});

blobService.createContainerIfNotExists('mycont',function(error, result, 
response) {
    if (error) {
        alert('Container Failed created');
    }
    else{
        let blockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 
    * 512;
        const options = {
            blockSize : blockSize
        };
        blobService.singleBlobPutThresholdInBytes = blockSize;

        let finishedOrError = false;
        let speedSummary = 
        blobService.createBlockBlobFromBrowserFile("mycont", file.name, file, 
         options, function(error, result, response) {
        finishedOrError = true;
        if (error) {
            alert('Upload failed, open browser console for more detailed 
              info.');
            console.log(error);
        } else {
            alert('ok.');
        }
    });
}
});

but I'm getting this error:

Failed to load resource: the server responded with a status of 403 (CORS not enabled or no matching rule found for this request.)

Failed to load http://127.0.0.1:10000/devstoreaccount1/?comp=properties&restype=service: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.

2
Any update? You could accept one useful answer or post method you found valid.Jerry Liu

2 Answers

0
votes

As Jerry Liu said above, we need to config CROS of azure store emulator.

We can do as below:

$ErrorActionPreference = "Stop";

# config

$AccountName='your account name'
$AccountKey='your account key'

# derived config

$BlobEndpoint="http://127.0.0.1:10000/$($AccountName)"
$QueueEndpoint="http://127.0.0.1:10001/$($AccountName)"
$TableEndpoint="http://127.0.0.1:10002/$($AccountName)"

$ConnectionString = "" +
    "DefaultEndpointsProtocol=http;" + 
    "BlobEndpoint=$($BlobEndpoint);" +
    "QueueEndpoint=$($QueueEndpoint);" +
    "TableEndpoint=$($TableEndpoint);" +
    "AccountName=$($AccountName);" +
    "AccountKey=$($AccountKey)"

# authentication

    $Context = New-AzureStorageContext `
    -ConnectionString $ConnectionString

# cors rules
$CorsRules = (@{
    AllowedHeaders=@("*");
    AllowedOrigins=@("*");
    ExposedHeaders=@("Content-Length");
    MaxAgeInSeconds=60*60*24;
    AllowedMethods=@("Get", "Post")
})

Set-AzureStorageCORSRule `
    -ServiceType Table `
    -Context $Context `
    -CorsRules $CorsRules

# check
Get-AzureStorageCORSRule `
    -ServiceType Table `
    -Context $Context

Similar thread for your reference:

How do i add a CORS rule to the Azure Storage Emulator with HTTP?

0
votes

CORS is used to set whether the service you request allows your js script from browser in different domain. It means all requests sent from browser need CORS check, including setServiceProperties.

So you need to create a separate file to execute CORS settings as a back-end operation. For example, you can use nodejs to run your setServiceProperties.

  1. Install nodejs.
  2. In one folder, open any command line tools like cmd on windows, input npm install azure-storage to install storage module for script to use.
  3. Create one setcors.js file in this folder.

    const azure = require('azure-storage');
    const devStoreCreds  = azure.generateDevelopmentStorageCredentials();
    const blobService = azure.createBlobService(devStoreCreds);
    
    const serviceProperties = {
        Cors: {
            CorsRule: [{
                AllowedOrigins: ['*'],
                AllowedMethods: ['POST', 'PUT','HEAD'],
                AllowedHeaders: ['*'],
                ExposedHeaders: ['*'],
                MaxAgeInSeconds: 200
            }]
        }
    };
    
    blobService.setServiceProperties(serviceProperties, function(error, result, response) {
        if (error) {
            console.log(error);
        }
    });
    
  4. In cmd, input node setcors.js to run your script. No message means it executes successfully.

  5. If you got exception prompt you to get latest version storage emulator, just follow the link to install it.

Note that method HEAD is included in AllowedMethods because it's used in createContainerIfNotExists.

Also you can use storage-explorer to set CORS.

Storage Accounts->(Development)->right click on Blob Container. Configure CORS settings as your wish.

enter image description here