javascript - 如何在 firebase 函数环境中解决 CORS?

标签 javascript firebase promise google-cloud-functions

我遇到了CORS问题。在我的 functions/index.js我有:

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

我的端点是 https://sis-t.redsys.es:25443/sis/realizarPago .我需要做一个 POST使用来自客户端的适当参数到这个 url,这是在 firebase 环境之外。我也有允许外部网络的正确计划,但是向与原始地址不同的地址发出请求会触发 CORS问题:
  • error log
  • network log

  • 我已经读到您只需要修改 header ,但这仅适用于您向自己的服务器发出请求时。当您执行 http.onRequest() ,您可以在函数内部使用中间件,但是当您向外部服务器进行 POST 时会发生什么?

    这是axios执行 POST 的函数:
    cardPay: function () {
      this.cardProcess = true
        axios({
          method: 'post',
          url: 'https://us-central1-cutre-windrider.cloudfunctions.net/cardPay',
          data: {
            verifiedUserLogged: this.userLogged.uid,
            cart: this.cartItemList,
            finalPrice: this.serverPrice,
            deliveryInfo: this.userLogged.deliveryAdress,
            name: this.userLogged.displayName || false,
            email: this.userLogged.email
          }
        })
        .then(response => {
          this.requestData = response
          this.redsysRedirect(response.data.data)
        })
        .catch(console.log)
        },
    redsysRedirect: function (data) {
      axios.post('https://sis-t.redsys.es:25443/sis/realizarPago', {
        'Ds_SignatureVersion': 'HMAC_SHA256_V1',
        'Ds_MerchantParameters': data.merchantParameters,
        'Ds_Signature': data.signature
      }).then(console.log).catch(console.log)
    

    这些是服务器端功能:
    exports.cardPay = functions.https.onRequest((req, res) => {
      return cors(req, res, () => {
        const cart = req.body.cart
        const user = req.body.verifiedUserLogged
        const key = admin.database().ref(`sales/${user}`).push().key
        processCart(cart).then(result => {
          console.info(createPayment(result, key))
          return res.json({ "data": createPayment(result, key) }).end()
        }).catch(console.log)
      })
    })
    
    function processCart(cart) {
      return new Promise((resolve, reject) => {
        Promise.all(cart.map(i => switcher(i)))
          .then(prices => resolve(
            prices.reduce(
              (finalPrice, price) => price + finalPrice, 0)
          )).catch(console.log)
      });
    }
    
    function switcher(item) {
      switch (item.destiny) {
        case 'bookedLessons':
            return lessonPrice(item.name, item.index)
          case 'bookedRentals':
            return rentalPrice(item.id, item.index, item.insurancePurchased, item.insuranceId)
          case 'bookedLodgins':
            return item.reservationData ? roomPriceWithReservation(item.id, item.quantity, item.persons, item.reservationData) : roomPriceNoReservation(item.id, item.quantity, item.persons)
          case 'deliveries':
            return productPrice(item.id, item.quantity)
          case 'bookedCar':
            return carPrice(item.id, item.index)
          case 'bookedStorage':
            return storagePrice(item.index)
          case 'bookedTransportation':
            return transportationPrice(item.id, item.index, item.persons, item.roundTrip)
          case 'bookedDoublePack':
            return doublePack(item.id, item.persons)
          case 'bookedTriplePack':
            return triplePack(item.id, item.persons)
          default:
            break
      }
    }
    
    function createPayment(total, orderId) {
      let redsys = new Redsys();
      let mParams = {
          "DS_MERCHANT_AMOUNT":total.toString(),
          "DS_MERCHANT_ORDER":orderId,
          "DS_MERCHANT_MERCHANTCODE":   "025988262",
          // "DS_MERCHANT_MERCHANTCODE":tpvInfo.fucCode,
          "DS_MERCHANT_CURRENCY":"978",
          // "DS_MERCHANT_CURRENCY":tpvInfo.currency,
          "DS_MERCHANT_TRANSACTIONTYPE":"0",
          // "DS_MERCHANT_TRANSACTIONTYPE":tpvInfo.transaction_type,
          "DS_MERCHANT_TERMINAL":   "001",
          // "DS_MERCHANT_TERMINAL":tpvInfo.terminal,
          "DS_MERCHANT_MERCHANTURL":'http://localhost:8080',
          "DS_MERCHANT_URLOK":'http://localhost:8080/home?foo=true',
          "DS_MERCHANT_URLKO":'http://localhost:8080/home?foo=false'
      };
      return  {signature: redsys.createMerchantSignature(/* tpvInfo.secret */   "sq7HjrUOBfKmC576ILgskD5srU870gJ7", mParams) , merchantParameters: redsys.createMerchantParameters(mParams), raw: mParams};
    }
    

    最佳答案

    对于将来会遇到此问题的人(或我 future 的自己):

    如果您已经使用 cors 配置了 CORS包,并且您认为您配置正确,并且在浏览器控制台中仍然出现CORS错误,请查看这篇文章:

    https://haha.world/firebase-cors/

    基本上,这是从 Google Cloud Functions 返回的误导性错误,而实际上错误在您的代码逻辑中(这与 CORS 完全无关)

    因此,修复此错误的第一步是检查 Google Cloud Functions 日志(或 Firebase Cloud Functions 日志),以查看您的函数是否因代码中的任何错误而崩溃。然后修复它。

    备注 :对于没有我上面描述的问题的人,您可以查看其他答案,或查看以下资源:

  • https://expressjs.com/en/resources/middleware/cors.html
  • https://firebase.google.com/docs/functions/http-events#using_existing_express_apps
  • 关于javascript - 如何在 firebase 函数环境中解决 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597210/

    相关文章:

    javascript - 如何使用事件和 promise 来控制程序流?

    javascript - javascript中具有不同类型和值的运算符

    javascript - js函数从url获取文件名

    android - RecyclerView 未预览

    java - 如何为手机中安装的 Whatsapp、Facebook 或其他应用程序创建共享按钮

    javascript - 如何将现有回调 API 转换为 Promise?

    javascript - 外部接口(interface)在 IE 中不起作用

    javascript - 比较两个输入字段中的值

    ios - 使用新的 Firebase Messaging SDK 在 iOS 中发送通知

    javascript - 使用自定义错误退出/违背 promise