目前我有以下功能:
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 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;
}
}
但是我收到了以下来自Response类型的返回:
body: (...) // it's null
bodyUsed: false
headers: Headers {} // empty
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
__proto__: Response
我尝试使用.blob()和.json(),但我无法获得我要发送到前端的数据。我做错了什么?
2条答案
按热度按时间uyhoqukh1#
const body = JSON.parse(request.body)
并不像你在云函数中所想的那样。对于JSON内容类型的POST,request.body
预先填充了反序列化的JSON。请参阅有关处理内容类型的文档。不需要解析request.body
,只需将其用作普通JS对象即可。如果您必须自己处理请求的解析,可以使用
request.rawBody
,但我认为这不会给您带来任何好处。uxhixvfz2#
您可能需要确保
motoristas.val()
的发送类型与send
API兼容。参见related answer。