HTTP 事件云函数:请求正文值未定义 [英] HTTP Event Cloud Function: request body value is undefined

查看:31
本文介绍了HTTP 事件云函数:请求正文值未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当发送 {"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆