首页 > 解决方案 > 为什么 Firestore Cloud Function 返回错误的请求响应?

问题描述

我正在关注 firebase 的 youtube 频道上关于使用自定义声明进行授权的教程。在尝试调用云函数时,我不断收到来自 firebase 服务器的“错误请求:无效参数”响应。该函数甚至从未被调用。我猜测data结构不正确(无效参数),但不知道为什么。有人可以解释一下吗?

云功能:

exports.addAdmin = functions.https.onCall( (data: any, context: any) => {
  const email = data.email;
  return grantAdminRole(email).then(() => {
    return{
      result: 'Admin role has been assigned successfully'
    }
  }).catch( err => {
    return{
      error: err
    }
  })
})

async function grantAdminRole(email: string): Promise<void> {
  const user = await admin.auth().getUserByEmail(email);
  if( user.customClaims && user.customClaims.admin === true ) {
    return;
  } else {
    return admin.auth().setCustomUserClaims(user.uid, {
      admin: true
    })
  }
};

客户:

endpoint = 'https://[MY_FUNCTION_URL]';
userEmail = 'test@test.com';

constructor( private http: HttpClient ) {}

grantAdminRole() {
  this.http.post(this.endpoint, this.userEmail ).subscribe( res => {
    console.log(res);
  });
}

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functionsangularfire2

解决方案


您的服务器端实现了一个可调用的Cloud Functions,如下所示:

functions.https.onCall

但是您的客户端随后尝试将其作为HTTP 云函数调用:

this.http.post(this.endpoint, ...

虽然可调用函数构建在 HTTP 函数之上,但它们不能以相同的方式调用。您应该使用客户端函数 SDK调用可调用的 Cloud Function,或者实现有线协议


推荐阅读