I get this error:
localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
import React, { useState, useEffect } from 'react';
import axios from 'axios'
import { SecretClient } from '@azure/keyvault-secrets';
import { useMsal, useIsAuthenticated } from '@azure/msal-react'
const App = () => {
const { instance } = useMsal()
const [secretValue, setSecretValue] = useState('');
useEffect(() => {
const CurrentAccount = instance.getActiveAccount()
const request = {
scopes: ['openid', 'profile', 'user.read', 'user.read.all'],
account: CurrentAccount
}
const response = await instance.acquireTokenSilent(request)
console.log(response.accesstoken)//to get accesstoken code with single sign on.
const getSecret = async () => {
const vaultName = '<YOUR_KEY_VAULT_NAME>';
const url = `https://${vaultName}.vault.azure.net/secrets/<YOUR_SECRET_NAME>?api- version=7.0`;
const headers = {
Authorization: `Bearer ${response.accesstoken}`
};
try {
const response1 = await axios.get(url, { headers });
setSecretValue(response1.data.value);
} catch (error) {
console.error('Error retrieving secret:', error);
}
};
getSecret();
}, []);
return (
<div>
<p>Secret value: {secretValue}</p>
</div>
);
};
export default App;
When making requests to Azure Key Vault, we need to check that the server or Azure Function allows requests from the domain where the React application is hosted.
Access-Control-Allow-Origin
header.In portal:
await
keyword is used outside an asynchronous function.Result: