[英]How can I view the body data of an HTTP request in a Firebase Functions JS?
"I'm trying to view the body data in a Firebase Functions POST request, but the console always returns "undefined" in the Firebase function logs! “我正在尝试查看 Firebase Functions POST 请求中的正文数据,但控制台始终在 Firebase function 日志中返回“未定义”!
Question: How can I view the body data in a Firebase function to use it?问题:如何查看Firebase function中的身体数据来使用?
Here My Code:这是我的代码:
exports.test = functions.https.onRequest(async (req, res) => {
const id = req.body.id
});
I allready used but not working:我已经使用但没有工作:
req.on('data', (chunk) => {
// The chunk is a Buffer object containing a chunk of the request body data
body += chunk;
}).on('end', () => {
// The request body data has been fully received, and the `body` variable contains the complete request body
});
i should to get id from body.id我应该从 body.id 获取 id
As per this thread's answer you should use Content-Type
and make it to "application/json" as only then your body will be accessible like as shown in here根据该线程的回答,您应该使用
Content-Type
并将其设置为“application/json”,因为只有这样您的身体才能像此处所示那样访问
Also you can check out Read values from the request which explains the need of application/json
on Content Type
.您还可以查看请求中的读取值,其中解释了
application/json
对Content Type
的需求。
If you check the firebase functions logs you can see there is no incoming body received from the request and because of that your body content's are undefined.如果您检查 firebase 函数日志,您可以看到没有从请求中收到传入正文,因此您的正文内容未定义。
There is also a possibility that the req.body
property in a Firebase Functions is not properly formatted or if it is not properly parsed by the Function, so you can force it to parse using JSON.parse(req.body);
也有可能是 Firebase 函数中的
req.body
属性格式不正确,或者它没有被 Function 正确解析,所以你可以使用JSON.parse(req.body);
to parse the request body.解析请求正文。 So the updated code will something look like:
所以更新后的代码看起来像这样:
exports.test = functions.https.onRequest(async (req, res) => {
const body = JSON.parse(req.body);
const id = body.id;
// ...
});
OR要么
You can use the body parser middleware and force parse the body as JSON as shown in this answer
您可以使用正文解析器中间件并将正文强制解析为 JSON ,如此答案所示
req.body can be used if the request body type is application/json or application/x-www-form-urlencoded otherwise use req.rawBody如果请求主体类型是 application/json 或 application/x-www-form-urlencoded 则可以使用req.body否则使用req.rawBody
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.