Firebase功能-无法读取要求正文

时间:2019-06-29 17:35:38

标签: node.js firebase express google-cloud-functions

我的Firebase Functions https请求有问题。

这是我触发它的代码:

  const express = require('express');
  const bodyParser = require('body-parser');
  const app = express();
  app.use(bodyParser.json());
  app.use(function(req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, POST");
    next();
  });
  app.use((err, req, res, next) => {
    if (err instanceof SyntaxError) {
      return res.status(400).send();
    };

    next();
  });
  app.post('/fetchPosts', (req, res) => {
    exports.fetchPosts(req, res);
  });

  exports.widgets = functions.https.onRequest(app);

  const cors = require('cors')({ origin: true })
  exports.fetchPosts = (req, res) => {
      console.log(req.body)
      console.log(res)
    let topics = req.body.topics || ['live'];
    let start = req.body.start || 0;
    let num = req.body.num || 10;
    let next = start+num;
    // setting up the response.
  });

据我所知,这看起来不错。

现在,当我进行api调用时,我会做:

   var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    const request = new RequestOptions({ headers: headers });
    const url = 'https://my-link.cloudfunctions.net/widgets/fetchPosts';
    let payload = {
        topics: ["live", "pets"]
    }
    console.log(JSON.stringify(payload))
    this.http.post(url, JSON.stringify(payload), request)
    .pipe(map((res:Response) => {
      console.log(res.json())
    }))
    .subscribe(
      data => console.log(data),
      err => console.log(err),
      () => console.log('Got feed')
    );

,它只返回topics并返回['live'] ..因为我在后端设置了故障保护功能。但是为什么不让我的topics发送?

此外,当我在后端console.log(req.body)上显示{} ..一个空对象时。

有什么想法为什么req.body似乎不起作用?我也使用startnum来做到这一点,但是它们都恢复了故障保护功能。

1 个答案:

答案 0 :(得分:0)

您必须使用POST方法来处理req.body。您可以使用req.query

处理变量

要处理req.body。您可以使用Postman,然后选择POST方法并将数据发布为JSON。您可以阅读more来很好地使用 Postman