Qwe*_*rty 26 firebase google-cloud-functions
通过文档,我遇到了:
...您可以直接使用HTTP请求或来自客户端的调用来调用函数.
〜来源
那里(引用中的链接)是一个提及functions.https.onCall.
但是在这里的教程中,使用了另一个函数functions.https.onRequest,我应该使用哪个函数?为什么?它们之间有什么区别/相似之处?
文档functions.https是在这里.
Qwe*_*rty 39
这些官方文档确实很有帮助,但从业余人士的角度来看,所描述的差异最初令人困惑.
可以直接从客户端应用程序调用(这也是主要目的).
functions.httpsCallable('getUser')({uid})
.then(r => console.log(r.data.email))
Run Code Online (Sandbox Code Playgroud)它由用户提供data和自动化实现 context.
export const getUser = functions.https.onCall((data, context) => {
if (!context.auth) return {status: 'error', code: 401, message: 'Not signed in'}
return new Promise((resolve, reject) => {
// find a user by data.uid and return the result
resolve(user)
})
})
Run Code Online (Sandbox Code Playgroud)context自动的包含元数据有关请求如uid和token.data和response对象自动(反)序列化.它用express Request和Responseobjects实现.
export const getUser = functions.https.onRequest((req, res) => {
// verify user from req.headers.authorization etc.
res.status(401).send('Authentication required.')
// if authorized
res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(user))
})
Run Code Online (Sandbox Code Playgroud)阅读更多内容新的Firebase云功能https.onCall触发器更好吗?
R..*_*... 15
客户端的onCall和onRequest之间的主要区别在于它们从客户端调用的方式。当您使用onCall定义函数时,例如
exports.addMessage = functions.https.onCall((data, context) => {
// ...
return ...
});
Run Code Online (Sandbox Code Playgroud)
您可以使用 firebase 函数客户端 SDK 在客户端调用它,例如
// on the client side, you need to import functions client lib
// then you invoke it like this:
const addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
});
Run Code Online (Sandbox Code Playgroud)
onCall 的更多信息:https ://firebase.google.com/docs/functions/callable
但是如果你使用onRequest定义你的函数,例如
exports.addMesssage = functions.https.onRequest((req, res) {
//...
res.send(...);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用普通的 JS fetch API 调用它(无需在客户端代码上导入 firebase 函数客户端库)例如
fetch('<your cloud function endpoint>/addMessage').then(...)
Run Code Online (Sandbox Code Playgroud)
这是您在决定如何在服务器上定义函数时需要考虑的巨大差异。
onRequest 的更多信息: https: //firebase.google.com/docs/functions/http-events
| 归档时间: |
|
| 查看次数: |
7869 次 |
| 最近记录: |