Firebase Functions中请求体email变量查询时未定义问题排查
Firebase Functions中请求体email变为undefined的问题排查
问题描述
在Firebase Functions中执行数据库查询时,请求体(request body)中的email变量会变为undefined,但硬编码email值时却能正常运行。
相关代码
exports.verify_email_otp = functions.https.onRequest(async (request, response) => { response.set("Access-Control-Allow-Origin", "*"); response.set("Access-Control-Allow-Headers", "Content-Type"); const email = request.body.email; const otp = request.body.otp; console.log("email"); console.log(email); const emailList = await admin.database().ref("/email_auth_requests").orderByChild("email").equalTo(email).once('value'); // 被认为导致email变为undefined的行 const listData = emailList.val(); console.log(listData); console.log("otp is: ",listData.otp); if(listData){ if(email){ if(parseInt(listData.otp) === parseInt(otp)){ let userRecord; try{ console.log(email); userRecord = await admin.auth().getUserByEmail(email); } catch (error){ console.log(error); response.send({ error: "Error finding email" }); userRecord = await admin.auth().createUser({ email: email, emailVerified: true }); } try{ const customToken = await admin.auth().createCustomToken(userRecord.uid); response.send({ token: customToken }); } catch (error){ console.log(error); response.send({ error: "Error creating custom token" }); } } else { response.send({ error: "OTP mismatch" }); } }else{ response.send({ error: "Request email not found" }); } }else{ response.send({ error: "Request email not found" }); } });
日志截图

可能原因及解决建议
可能原因
- 请求内容类型不匹配:前端发送请求时未设置
Content-Type: application/json,Firebase Functions基于的Express框架无法正确解析JSON请求体,导致request.body本身为空,自然取不到email值。 - 混淆因果关系:并非数据库查询导致email变为undefined,而是初始就没从请求体中拿到email,导致数据库查询返回空结果,触发后续错误分支,让你误以为是查询导致的变量异常。
- 未处理OPTIONS预请求:前端发起跨域请求时会先发送OPTIONS预请求,该请求无请求体,此时
request.body.email必然是undefined,如果函数没有正确处理OPTIONS请求,会干扰后续正常请求的判断。
解决建议
- 校验前端请求格式:确保前端发送POST请求时,设置
Content-Type为application/json,且请求体是合法的JSON字符串。 - 添加请求体日志:在函数最开头添加
console.log("完整请求体:", request.body),确认请求体是否被正确解析。 - 处理OPTIONS预请求:在函数开头加入逻辑处理OPTIONS请求,避免预请求触发业务逻辑:
if (request.method === 'OPTIONS') { response.status(204).send(''); return; } - 提前校验参数:在执行数据库查询前,先校验email和otp是否存在,避免无效查询:
if (!email || !otp) { response.status(400).send({ error: "缺少必要参数:email或otp" }); return; }
内容的提问来源于stack exchange,提问作者jahanzaib
相关产品推荐
相关产品推荐

