问题描述
在 React 中通过 fetch() 调用 API 但收到 CORS 错误。 https://login.microsoftonline.com/tenant_id/oauth2/v2.0/authorize?client_id=xxxxxxxxxxxxxxxxxxxxx&response_type=code&redirect_uri=http://localhost:3050&scope=user.Read.All&response_mode=query
以上 URL 由 Postman 制作,如果直接粘贴在浏览器上可以正常工作。
2.有没有办法安全地获取代码,即在正文中而不是在查询中获取响应代码?
尝试将 Allow-access-origin 的 fetch 中的标头传递给 *。
解决方法
我们需要 use msal 做出反应以避免 CORS 问题。微软还提供了一些 react 应用的示例,你可以看到 this document。我在这里测试了 this sample code。我还注册了一个 azure 广告应用程序并设置了重定向 url http://locahost:3000,这是我的配置:
enter image description here enter image description here
正如你在 App.jsx 中看到的,它使用下面的代码来生成访问令牌并用它调用图 api,不需要在浏览器中显示身份验证代码,因为令牌是静默获取的。我认为这可以满足您的要求。
function RequestProfileData() {
// Silently acquires an access token which is then attached to a request for MS Graph data
instance.acquireTokenSilent({
...loginRequest,account: accounts[0]
}).then((response) => {
callMsGraph(response.accessToken).then(response => setGraphData(response));
});
}
========================更新==================
对于您的问题 2,我认为 this may help you: