如何使用fetch获取从Firebase函数返回的数据?

t1qtbnec  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(219)

目前我有以下功能:

  1. exports.loginDriver = functions.https.onRequest(async (request, response) => {
  2. try {
  3. const body = JSON.parse(request.body);
  4. const motorista = await admin
  5. .database()
  6. .ref(`motoristas/${body.cpf}`)
  7. .once("value");
  8. // Se não existe o token, motorista não cadastrado
  9. if (motorista.val().token === null || motorista.val().token === undefined) {
  10. response.status(400).send({ error, message: "Motorista não encontrado" });
  11. } else {
  12. const bytes = AES.decrypt(motorista.val().token, motorista.val().cpf);
  13. const senha = bytes.toString(enc);
  14. if (senha === body.senha) {
  15. response.status(200).send(motorista.val());
  16. } else {
  17. response.send(400).send({ message: "CPF ou senha inválidos" });
  18. }
  19. }
  20. } catch (error) {
  21. response.status(400).send({ error, message: "Erro ao realizar o login" });
  22. }
  23. });

我在前端这样调用它:

  1. async doLogin() {
  2. const loading = await this.loadingCtrl.create({backdropDismiss: false, message: 'Aguarde...'});
  3. await loading.present();
  4. try {
  5. if (this.loginForm.valid) {
  6. this.formInvalid = false;
  7. const user: Response = await this._auth.login(this.loginForm.value);
  8. console.log('response', await user.json());
  9. await this._storage.set('user', user);
  10. await loading.dismiss();
  11. await this.navCtrl.navigateRoot('/home');
  12. } else {
  13. this.formInvalid = true;
  14. await loading.dismiss();
  15. alert('Preencha os dados corretamente');
  16. }
  17. } catch (error) {
  18. await loading.dismiss();
  19. console.log(error);
  20. }
  21. }
  22. /* My _auth service which has the login method */
  23. async login(data) {
  24. try {
  25. return await fetch('https://myCloudFunctionsUrl/loginDriver', {
  26. body: JSON.stringify(data),
  27. method: 'POST',
  28. mode: 'no-cors',
  29. headers: {
  30. 'Content-Type': 'application/json'
  31. }
  32. });
  33. } catch (error) {
  34. return error;
  35. }
  36. }

但是我收到了以下来自Response类型的返回:

  1. body: (...) // it's null
  2. bodyUsed: false
  3. headers: Headers {} // empty
  4. ok: false
  5. redirected: false
  6. status: 0
  7. statusText: ""
  8. type: "opaque"
  9. url: ""
  10. __proto__: Response

我尝试使用.blob()和.json(),但我无法获得我要发送到前端的数据。我做错了什么?

uyhoqukh

uyhoqukh1#

const body = JSON.parse(request.body)并不像你在云函数中所想的那样。对于JSON内容类型的POST,request.body预先填充了反序列化的JSON。请参阅有关处理内容类型的文档。不需要解析request.body,只需将其用作普通JS对象即可。
如果您必须自己处理请求的解析,可以使用request.rawBody,但我认为这不会给您带来任何好处。

uxhixvfz

uxhixvfz2#

您可能需要确保motoristas.val()的发送类型与send API兼容。
参见related answer

相关问题