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

问题描述 投票:0回答:1

当前我具有以下功能:

exports.loginDriver = functions.https.onRequest(async (request, response) => {
  try {
    const body = JSON.parse(request.body);
    const motorista = await admin
      .database()
      .ref(`motoristas/${body.cpf}`)
      .once("value");

    // Se não existe o token, motorista não cadastrado
    if (motorista.val().token === null || motorista.val().token === undefined) {
      response.status(400).send({ error, message: "Motorista não encontrado" });
    } else {
      const bytes = AES.decrypt(motorista.val().token, motorista.val().cpf);
      const senha = bytes.toString(enc);
      if (senha === body.senha) {
        response.status(200).send(motorista.val());
      } else {
        response.send(400).send({ message: "CPF ou senha inválidos" });
      }
    }
  } catch (error) {
    response.status(400).send({ error, message: "Erro ao realizar o login" });
  }
});

而且我从前端这样称呼它

async doLogin() {
    const loading = await this.loadingCtrl.create({backdropDismiss: false, message: 'Aguarde...'});
    await loading.present();
    try {
      if (this.loginForm.valid) {
        this.formInvalid = false;
        const user: Response = await this._auth.login(this.loginForm.value);
        console.log('response', await user.json());
        await this._storage.set('user', user);
        await loading.dismiss();
        await this.navCtrl.navigateRoot('/home');
      } else {
        this.formInvalid = true;
        await loading.dismiss();
        alert('Preencha os dados corretamente');
      }
    } catch (error) {
      await loading.dismiss();
      console.log(error);
    }
  }

/* My _auth service wich has the login method */
async login(data) {
    try {
      return await fetch('https://myCloudFunctionsUrl/loginDriver', {
        body: JSON.stringify(data),
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'application/json'
        }
      });
    } catch (error) {
      return error;
    }
  }

但是我收到以下返回值来自响应类型:

body: (...) // it's null
bodyUsed: false
headers: Headers {} // empty
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response

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

javascript firebase google-cloud-functions fetch httprequest
1个回答
0
投票

const body = JSON.parse(request.body)不能满足您在Cloud Functions中的想法。对于具有JSON内容类型的POST,request.body会预填充反序列化的JSON。请参阅handling content types上的文档。不用解析request.body,只需将其用作普通的JS对象即可。

如果绝对必须自己处理请求的解析,则可以改用request.rawBody,但我认为这不会给您带来任何好处。

© www.soinside.com 2019 - 2024. All rights reserved.