【问题标题】:Firebase Functions - cannot read req.bodyFirebase 函数 - 无法读取 req.body
【发布时间】:2019-11-11 03:48:38
【问题描述】:

我的 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 进行此操作,但它们都恢复为故障保护。

【问题讨论】:

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


    【解决方案1】:

    您必须使用 POST 方法来处理 req.body 。在您的情况下,您可以使用 req.query

    处理您的变量

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

    【讨论】:

    • 我更新了我的代码,使其成为post.. 但我仍然遇到同样的问题.. 有什么想法吗?
    • 你可以试试:` app.post('/fetchPosts', (req, res) => { console.log(req.body) // 处理请求 }); `
    • 我不得不在 firebase shell 中像这样调用 post 来获取 req.body 数据:createPaymentIntent.post().form({amount: 777, currency: "usd"})
    猜你喜欢
    • 2021-09-30
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    相关资源
    最近更新 更多