我的客户端代码只调用了一次函数,但在服务器日志中,它显示了两次单独的调用。不过,每对中的第一个似乎并没有真正处理我的服务器端代码——这是预期的行为吗?
onCall功能:
const functions = require('firebase-functions');
exports.test = functions
.region('asia-northeast1')
.https
.onCall(async (data, context) => {
console.log('function test: start')
if (!context.auth) {
console.log('function test: throwing permission-denied');
throw new functions.https.HttpsError('permission-denied', 'Mysterious');
}
console.log('function test: no error, user authorised');
});
客户端HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<script defer src="/__/firebase/7.7.0/firebase-app.js"></script>
<script defer src="/__/firebase/7.7.0/firebase-auth.js"></script>
<script defer src="/__/firebase/7.7.0/firebase-firestore.js"></script>
<script defer src="/__/firebase/7.7.0/firebase-messaging.js"></script>
<script defer src="/__/firebase/7.7.0/firebase-storage.js"></script>
<script defer src="/__/firebase/7.7.0/firebase-functions.js"></script>
<script defer src="/__/firebase/init.js"></script>
</head>
<body>
<script src="app.js"></script>
<button onclick="login()">
Login with Google
</button>
<button onclick="logout()">
Log out
</button>
<button onclick="test()">
test
</button>
</body>
</html>
客户端JS:
var user, app, functions, callableTest;
document.addEventListener("DOMContentLoaded", async event => {
app = firebase.app();
functions = app.functions('asia-northeast1');
callableTest = functions.httpsCallable('test');
user = await firebase.auth().currentUser;
console.log('user: ' + user);
});
async function login() {
user = await firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
async function logout() {
await firebase.auth().signOut();
user = null;
}
async function test() {
console.log('calling test function');
await callableTest();
console.log('returned from test function');
}
以下是[测试]的日志,单击预登录,然后单击[登录..],然后再次单击[测试]:
日志图像
D 2020-02-22T04:08:27.209014265Z test 7whrcrhllsa8 Function execution took 5 ms, finished with status code: 403 test 7whrcrhllsa8
I 2020-02-22T04:08:27.208Z test 7whrcrhllsa8 function test: throwing permission-denied test 7whrcrhllsa8
I 2020-02-22T04:08:27.208Z test 7whrcrhllsa8 function test: start test 7whrcrhllsa8
D 2020-02-22T04:08:27.205019518Z test 7whrcrhllsa8 Function execution started test 7whrcrhllsa8
D 2020-02-22T04:08:27.072797567Z test 7whrdta870ib Function execution took 42 ms, finished with status code: 204 test 7whrdta870ib
D 2020-02-22T04:08:27.031343424Z test 7whrdta870ib Function execution started test 7whrdta870ib
D 2020-02-22T04:07:39.540689974Z test 7whryp7xojaf Function execution took 87 ms, finished with status code: 403 test 7whryp7xojaf
当请求来自网页(在您的情况下就是这样(时,状态代码为204的调用是CORS飞行前请求的结果。可调用功能可自动处理CORS安全,因此所有这些都无需您的干预。
这在可调用函数的协议规范中有文档记录。