繁体   English   中英

无法通过 fetch 从客户端调用 Firebase Cloud Function

[英]Unable to call Firebase Cloud Function from client-side with fetch

我有几个遵循以下语法的 Firebase 云函数:

exports.sendText = functions.https.onCall((data, context) => {...

这总是很好,但我一直在努力解决我最近部署的这个新“帖子”function。 是这样定义的...

payment_app.post("/create-payment-intent", async (req, res) => {
    const { items } = req.body;

    // Create a PaymentIntent with the order amount and currency
    const paymentIntent = await stripe.paymentIntents.create({
        amount: calculateOrderAmount(items),
        currency: "usd",
        automatic_payment_methods: {
            enabled: true,
        },
    });

    res.send({
        clientSecret: paymentIntent.client_secret,
    });
});
exports.payment = functions.https.onRequest(payment_app)

这就是我从客户端调用它的方式。

function buyProduct(id, quantity) {
    fetch('payment_app/create-payment-intent', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            items: [
                { id: id, quantity: quantity }
            ]
        })
    }).then(res => {
        if (res.ok) return res.json()
        return res.json().then(json => Promise.reject(json))
    }).then(({ url }) => {
        console.log(url)
        Object.assign(document.createElement('a'), { target: '_blank', href: url }).click();
        var refreshVerify = setInterval(() => {
            let payment_status = localStorage.getItem("payment_status")
            if (payment_status) {
                clearInterval(refreshVerify)
                localStorage.removeItem("payment_status")
                if (payment_status === "success") {
                    console.log("payment success")
                } else if (payment_status === "cancel") {
                    console.log("payment cancel")
                } else {
                    console.log("error local_payment_status variable not valid")
                }
            }
        }, 1000)
    }).catch(e => {
        console.error(e.error)
    })
}

这样做会返回 404 not found 错误:

script.js:3849 POST http://localhost:1234/payment_app/create-payment-intent 404 (Not Found)
buyProduct @ script.js:3849
testFunction @ script.js:3845
(anonymous) @ script.js:1257
setTimeout (async)
showApp @ script.js:1242
parcelRequire.script.js.firebase/compat/app @ script.js:1209
newRequire @ script.75da7f30.js:47
(anonymous) @ script.75da7f30.js:81
(anonymous) @ script.75da7f30.js:120
script.js:3880 undefined

谁能帮我弄清楚我做错了什么? 如果重要的话,这是我的 firebase.json。 我想我这里可能有问题?

{
  "functions": {
    "engines": {
      "node": "14"
    },
    "source": "functions"
  },
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "payment_app/**",
        "function": "create-payment-intent",
        "destination": "/index.html"
      }
    ]
  }
}

在您的 Cloud Functions 代码中,您正在实现一个可调用的 function。 从关于可调用函数的文档中:

请务必记住,HTTPS 可调用函数与 HTTP 函数相似但不相同。 To use HTTPS callable functions you must use the client SDK for your platform together with the functions.https backend API (or implement the protocol).

所以你不能简单地fetch()来调用 function,因为它没有实现正确的协议。 相反,您应该按照有关从客户端应用程序代码调用 function的文档中所示调用它。

如果您在不存在可调用 SDK 的客户端平台上:

如果您想为在不受支持的平台上构建的应用程序添加类似的功能,请参阅https.onCall的协议规范

暂无
暂无

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

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