[英]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.