CORS 阻止对资源的访问:如何在 firebase 云功能中修复?

red*_*ift 5 node.js cors firebase fetch-api google-cloud-functions

是的,我有可怕的 CORS 问题(或者,至少看起来是这样)……我已经搜索并尝试了一些解决方案,但无济于事……

我使用 firebase 模拟器并在本地运行我的函数没有任何问题,但是当我部署该函数并尝试在本地主机客户端应用程序上使用 fetch() 发送 POST 请求时,我收到以下 CORs 浏览器控制台错误(它赢得了甚至无法访问服务器日志):

Access to fetch at 'https://us-central1-XXXX.cloudfunctions.net/deleteAsset' from origin 'http://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.

The FetchEvent for "https://us-central1-XXXXX.cloudfunctions.net/deleteAsset" resulted in a network error response: the promise was rejected.

Promise.then (async)
(anonymous) @ firebase-auth-sw.js:77
firebase-auth-sw.js:77 
        
 Uncaught (in promise) TypeError: Failed to fetch
    at firebase-auth-sw.js:77
Run Code Online (Sandbox Code Playgroud)

这是我的客户端获取请求:

UploadImage.vue

async deleteFile() {
      await fetch(
        'https://us-central1-XXXX.cloudfunctions.net/deleteAsset',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            public_id: this.imageSrc.public_id
          })
        }
      )
}
Run Code Online (Sandbox Code Playgroud)

然后我的 firebase 云函数是这样的:

/deleteAsset.js

import cloudinary from 'cloudinary'
import * as functions from 'firebase-functions'

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

cloudinary.config({
  cloud_name: functions.config().cloudinary.cloud_name,
  api_key: functions.config().cloudinary.api_key,
  api_secret: functions.config().cloudinary.api_secret,
  secure: true
})


export const deleteAsset = functions.https.onRequest((req, res) => {
  return cors(req, res, () => {
    try {
      functions.logger.log(req.body)
      cloudinary.v2.uploader.destroy(
        req.body.public_id,
        {
          invalidate: true
        },
        (error, result) => {
          if (error) {
            res.status(500).send(error)
          }

          res.status(200).send(result)
        }
      )
    } catch (error) {
      res.status(500).send('There was an error in deleteAsset function')
    }
  })
})
Run Code Online (Sandbox Code Playgroud)

有人发现任何问题或对我如何进一步解决此问题有任何建议吗?

red*_*ift 13

好吧,所以我修复了它......CORS 问题是由于云功能没有正确的 IAM 权限造成的。我在查看我的仪表板后怀疑它(Firebase 控制台上未显示,必须转到 Google Cloud 上的 Cloud Functions 才能看到它!)并注意到它缺少“允许未经身份验证”。所以,我手动删除了该函数并重新部署。现在一切都好啦!

在此输入图像描述