首页 > 解决方案 > 如何绕过 CORS 从 Blazor WebAssembly 调用 Firestore?(调用在 JavaScript 中)

问题描述

我正在使用 Blazor WebAssembly 构建一个简单的登录页面,并利用 JSInterop 编写 JS 函数以使用 Firebase/Firestore。我有一个函数,它使用 Firebase 方法通过简单的自定义表单登录用户,然后获取 id 令牌和用户 id,然后传递给另一个请求访问 Firestore 的函数。一切都可以通过 Postman 完美运行,但是当我在我的应用程序中运行此过程时,我被 CORS 错误阻止:

Access to fetch at 'https://firestore.googleapis.com/v1/projects/trailblazor-
5ba6f/databases/(default)/documents/users/JJNlKtvGMcUm7MjfkuJy6WdlMiO2' from origin 
'https://localhost:44318' has been blocked by CORS policy: Response to preflight request doesn't pass
access control check: It does not have HTTP ok status.

这是我在 Firestore 中访问用户数据的请求的代码(传入 id 令牌和用户 id):

async function sendToken(idToken, userId) {
    try {
        const response = await fetch(`https://firestore.googleapis.com/v1/projects/trailblazor-5ba6f/databases/(default)/documents/users/${userId}`, {
            headers: new Headers({
                'x-api-key': '**omitted for security**',
                'Authorization': 'Bearer ' + idToken,
                'Access-Control-Allow-Origin': 'https://localhost:44318',
                'Access-Control-Allow-Credentials': 'true',
                'Access-Control-Allow-Headers': 'Content-Type',
                'Content-Type': 'application/json'
            }),
            mode: 'cors'
        });
        const receivedResponse = await response.json();
        if (receivedResponse != null) {
            console.log(receivedResponse);
        }
    } catch (error) {
        return error.message;
    }
}

如您所见,我已经尝试了很多标题,但到目前为止没有任何效果。即使是我启用的支持 CORS 的 Chrome 扩展也无济于事。我曾考虑过制作代理服务器,但我不确定这是否有意义。我已经查看了 Firebase 文档,这应该是我可以访问 Firestore 的方式,就像我说的,一切都在 Postman 中完美运行(当然)。

标签: javascriptfirebasegoogle-cloud-firestorecorsblazor-webassembly

解决方案


首先,CORS 由服务器管理。您在请求中添加一些标头这一事实无济于事。如果允许 CORS 请求,服务器会根据传入请求的域设置适当的标头。

你做代理服务器是对的。您可以使用https://cors-anywhere.herokuapp.com/corsdemo,它是前端开发人员发出 CORS 请求的代理服务器。github页面在这里


推荐阅读