简体   繁体   English

如何使用 Firebase 主机修复被阻止的 CORS?

[英]How do I fix Blocked CORS with Firebase Hosting?

I have read many threads around this topic and I still can't wrap my head around it.我已经阅读了很多关于这个主题的话题,但我仍然无法理解它。

I've built a web app that allows users to crawl their website sitemap and add it to a document in Firebase. I'm using Firebase hosting to host the web app, which was pushed to a subdomain of mine.我已经构建了一个 web 应用程序,允许用户抓取他们的网站站点地图并将其添加到 Firebase 中的文档。我正在使用 Firebase 托管来托管 web 应用程序,该应用程序被推送到我的子域。

I am using this package to crawl the sitemap - https://www.npmjs.com/package/get-sitemap-links我正在使用这个 package 来抓取站点地图 - https://www.npmjs.com/package/get-sitemap-links

I get this error every time in production - "Access to XMLHttpRequest at 'https://www.userswebsite.com/page-sitemap.xml' from origin 'https://app.mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."我每次在生产中都会收到此错误 - “CORS 策略已阻止从源“https://app.mywebsite.com”访问“https://www.userswebsite.com/page-sitemap.xml”中的 XMLHttpRequest : 请求的资源上不存在 'Access-Control-Allow-Origin' header。”

I've not created any cloud functions for this web app but have read I have to enable CORS using a function. How can I do this?我没有为此 web 应用程序创建任何云功能,但已阅读我必须使用 function 启用 CORS。我该怎么做?

To enable CORS you have to install library in your function folder by using below command要启用CORS ,您必须使用以下命令在function文件夹中安装库

npm i cors --save

And import as shown below:并导入如下图:

const cors = require('cors')({origin: true});

You can also set CORS headers without any library using below snippet您还可以使用以下代码段在没有任何库的情况下设置CORS标头

response.set('Access-Control-Allow-Origin', '*');

For more information have a look at this documentation and this thread有关更多信息,请查看此文档此线程

If you are configuring CORS for HTTP function. Use the cors option to control which origins can access your function.如果您正在为 HTTP 配置CORS function。使用cors 选项来控制哪些来源可以访问您的 function。

If true, allows CORS on requests to this function. If this is a string or RegExp, allows requests from domains that match the provided value.如果为真,则允许 CORS 对此 function 的请求。如果这是一个字符串或正则表达式,则允许来自与提供的值匹配的域的请求。 If this is an Array, allows requests from domains matching at least one entry of the array.如果这是一个数组,则允许来自与数组的至少一个条目匹配的域的请求。 Defaults to true for https.CallableFunction and false otherwise. https.CallableFunction 默认为 true,否则为 false。

Signature:签名:
cors?: string | boolean | RegExp | Array<string | RegExp>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM