Google Cloud Function报错:Content-type为text/plain不正确如何解决?
问题根源
navigator.sendBeacon 发送纯字符串时,默认会将请求的 Content-Type 设为 text/plain,而你的Google Cloud Function大概率仅配置了处理 application/json 类型的请求,因此触发了"Request has incorrect content-type. text/plain"及后续的无效请求报错。
两种可行解决方案
方案1:调整前端代码,发送JSON格式请求
由于 sendBeacon 直接传字符串无法自定义Content-Type,需将userId包装为JSON对象,通过Blob指定正确的请求类型:
// React中的调用代码 const userId = '目标用户ID'; const payload = JSON.stringify({ userId }); const requestBlob = new Blob([payload], { type: 'application/json' }); navigator.sendBeacon('你的Cloud Function部署URL', requestBlob);
修改后请求的Content-Type会被设置为application/json,匹配多数Cloud Function的默认解析逻辑。
方案2:修改Cloud Function代码,兼容text/plain请求
若不想改动前端,可调整Cloud Function的逻辑,支持解析text/plain类型的请求体。以Node.js环境为例,修改后的代码如下:
exports.updateFirestoreField = async (req, res) => { let userId; // 根据Content-Type解析请求体 const contentType = req.get('content-type'); if (contentType === 'text/plain') { userId = req.body.trim(); } else if (contentType?.includes('application/json')) { userId = req.body.userId; } else { return res.status(400).send('Invalid request, unable to process'); } // 执行Firestore更新逻辑 try { await admin.firestore().collection('users').doc(userId).update({ // 填写你要更新的字段及值 lastActive: new Date() }); return res.status(200).send('Update successful'); } catch (err) { console.error('Update error:', err); return res.status(500).send('Update failed'); } };
这样Cloud Function就能同时处理text/plain和application/json两种类型的请求。
验证步骤
修改完成后重新部署Cloud Function,在React应用中测试调用,查看Cloud Function日志确认无Content-Type报错,同时检查Firestore中目标字段是否成功更新。
内容的提问来源于stack exchange,提问作者Owenn
相关产品推荐
相关产品推荐

