HTTP 事件云函数:请求正文值未定义 [英] HTTP Event Cloud Function: request body value is undefined
问题描述
当发送 {"identifiant": "iJXB5E0PsoKq2XrU26q6"}
到下面的云函数时,我无法在请求正文中获取 identifiant
值,它总是会返回 PROBLEMAS NO REQUEST
.
When sending {"identifiant": "iJXB5E0PsoKq2XrU26q6"}
to the below Cloud Function, I cannot get the identifiant
value in the request body and it will always return PROBLEMAS NO REQUEST
.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
exports.meusCandidatos = functions.https.onRequest((req, res) => {
const identifiant = req.body.identifiant;
if(identifiant) res.status(200).json('ok').end();
res.status(500).json('PROBLEMAS NO REQUEST').end();
});
推荐答案
不像 可调用函数,请求体不会自动解析,需要先解析后才能使用.
Unlike a Callable function, the body of a request is not parsed automatically and needs to be parsed before you can use it.
此外,json(...)
将在内部调用 end()
,因此您不需要两者.还要确保不要多次调用 end()
、send()
、json()
等,因为这会导致错误.
In addition, json(...)
will call end()
internally so you don't need both. Also make sure that you don't call end()
, send()
, json()
, etc. multiple times, as this will lead to errors.
const jsonParser = require('body-parser').json();
exports.meusCandidatos = functions.https.onRequest((req, res) => {
jsonParser(req, res, (err) => {
if (err) {
res.status(500).json({error: err.message});
return; // stop here
}
const identifiant = req.body.identifiant;
if (!identifiant) {
res.status(500).json({error: 'PROBLEMAS NO REQUEST'});
return; // stop here
}
// continue
res.status(200).json({ status: 'ok' });
})
});
这篇关于HTTP 事件云函数:请求正文值未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!