提问人:ABDUL ANEES 提问时间:11/14/2023 最后编辑:isherwoodABDUL ANEES 更新时间:11/17/2023 访问量:88
为什么会收到 Azure Key Vault No-cors 策略错误?
Why do I get an Azure key Vault No-cors policy error?
问:
我收到此错误:
localhost:3000' 已被 CORS 策略阻止:对预检的响应 请求未通过访问控制检查:否 “Access-Control-Allow-Origin”标头存在于请求的 资源。如果不透明的响应满足您的需求,请将请求的 mode 设置为“no-cors”以获取禁用 CORS 的资源。
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;
答:
0赞
Suresh Chikkam
11/14/2023
#1
向 Azure Key Vault 发出请求时,我们需要检查服务器或 Azure 函数是否允许来自托管 React 应用程序的域的请求。
- 在响应中设置相应的 CORS 标头。您可以通过添加标头来执行此操作。
Access-Control-Allow-Origin
module.exports = async function (context, req) {
context.res = {
status: 200,
headers: {
'Access-Control-Allow-Origin': '<Your React App Origin>',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
},
body: /* Your response body here */
};
};
在门户中:
- 我注意到您提供的代码存在问题。似乎存在缩进问题,请再次检查,并且关键字是在异步函数之外使用的。
await
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useMsal } from '@azure/msal-react'; // Remove SecretClient import
import logo from './logo.svg';
import './App.css';
function App() {
const { instance } = useMsal();
const [secretValue, setSecretValue] = useState('');
useEffect(() => {
const fetchData = async () => {
try {
const currentAccount = instance.getActiveAccount();
const request = {
scopes: ['openid', 'profile', 'user.read', 'user.read.all'],
account: currentAccount,
};
const response = await instance.acquireTokenSilent(request);
const vaultName = ' ';
const secretName = ' ';
const url = `https://${vaultName}.vault.azure.net/secrets/${secretName}?api-version=7.0`;
const headers = {
Authorization: `Bearer ${response.accessToken}`,
};
const response1 = await axios.get(url, { headers });
setSecretValue(response1.data.value);
} catch (error) {
console.error('Error retrieving secret:', error);
}
};
fetchData();
}, [instance]);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Secret value: <strong>{secretValue}</strong>
</p>
<p>
Learn <a
className="App-link"
href="https://reactjs.org"
rel="noopener noreferrer"
>
React
</a>
</p>
</header>
</div>
);
}
export default App;
结果:
评论