简体   繁体   English

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

[英]How to get data returned from a Firebase Function using fetch?

Currently I have the following function:目前我有以下function:

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" });
  }
});

And I call it from my frontend like this:我从我的前端这样称呼它:

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 which 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;
    }
  }

But I receive the following return which is from Response type:但我收到以下来自响应类型的返回:

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

I tried using.blob() and.json(), but I wasn't able to get the data I'm sending to my frontend.我尝试使用 .blob() 和 .json(),但无法获取发送到前端的数据。 What am I doing wrong?我究竟做错了什么?

const body = JSON.parse(request.body) doesn't do what you think in Cloud Functions. const body = JSON.parse(request.body)与您在 Cloud Functions 中的想法不同。 For a POST with JSON content type, request.body comes pre-populated with deserialized JSON.对于具有 JSON 内容类型的 POST, request.body预先填充了反序列化的 JSON。 See the documentation on handling content types .请参阅有关处理内容类型的文档。 Instead of parsing request.body , just use it as a normal JS object.而不是解析request.body ,只需将其用作普通的 JS object。

If you absolutely must handle parsing of the request on your own, you can use request.rawBody instead, but I don't think that will buy you anything.如果您绝对必须自己处理请求的解析,您可以使用request.rawBody代替,但我认为这不会给您带来任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用从Firebase返回的数据获取Javascript - Using data returned from Firebase fetch Javascript 如何获取从fetch()Promise返回的数据? - How to get data returned from fetch() promise? 如何使用 fetch 限制从 JSON 文件返回的数据量? - How to limit the amount of data returned from a JSON file using fetch? 如何从firebase获取简单的数组数据并获取它 - How to get simple array data from firebase and fetch it 如何使用Firebase中的Dialogflow实现来获取数据 - How to fetch data using Dialogflow Fulfillment from Firebase 如何在云功能中获取firebase数据库数据? - How to fetch firebase database data in cloud function? 如何从此Firebase代码获取返回的结果 - How to get the returned results from this firebase code 异步 Javascript - 使用 Fetch 从 Weather.gov 获取数据以更新页面,但返回的 promise 不再可用 - Async Javascript - Using Fetch to get Data from Weather.gov to update a page, but returned promise is no longer thenable 使用来自 firebase 的多个 id 获取数据 - fetch data using multiple ids from firebase Firebase功能用于从Firebase DB获取数据以进行推送通知 - Firebase function to fetch data from Firebase DB to make Push notification
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM