firebase - 在 Cloud Functions 中使用 Express 处理多部分/表单数据 POST

标签 firebase express google-cloud-functions busboy

我一直在尝试使用 Firebase 函数和 Express 处理 POST(多部分/表单数据),但它不起作用。在本地服务器上试过这个,它工作得很好。除了不包含在 Firebase 函数中之外,一切都相同。

除了搞砸了请求对象,它似乎也搞砸了 busboy 的工作方式。

我尝试了不同的解决方案 here但他们就是不工作。正如一位用户所提到的,传递给 busboy 的回调(在找到“字段”或完成数据处理时调用)永远不会被调用,函数只是挂起。

有任何想法吗?

这是我的函数代码以供引用:

const functions = require('firebase-functions');
const express = require('express');
const getRawBody = require('raw-body');
const contentType = require('content-type')
const Busboy = require('busboy');

const app = express();

const logging = (req, res, next) => {
  console.log(`> request body: ${req.body}`);
  next();
}

const toRawBody = (req, res, next) => {
  const options = {
      length: req.headers['content-length'],
      limit: '1mb',
      encoding: contentType.parse(req).parameters.charset
  };
  getRawBody(req, options)
      .then(rawBody => {
          req.rawBody = rawBody
          next();
      })
      .catch(error => {
          return next(error);
      });
};

const handlePostWithBusboy = (req, res) => {
  const busboy = new Busboy({ headers: req.headers });
  const formData = {};

  busboy.on('field', (fieldname, value) => {
      formData[fieldname] = value;
  });

  busboy.on('finish', () => {
      console.log(`> form data: ${JSON.stringify(formData)}`);
      res.status(200).send(formData);
  });

  busboy.end(req.rawBody);
}

app.post('/', logging, toRawBody, handlePostWithBusboy);

const exchange = functions.https.onRequest((req, res) => {
  if (!req.path) {
    req.url = `/${req.url}`
  }
  return app(req, res)
})
module.exports = {
  exchange
}

最佳答案

请阅读 documentation for handling multipart form uploads .

... if you want your Cloud Function to process multipart/form-data, you can use the rawBody property of the request.



因为方式云函数pre-processes some requests ,您可以预期某些 Express 中间件将无法工作,而这正是您遇到的问题。

关于firebase - 在 Cloud Functions 中使用 Express 处理多部分/表单数据 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48289824/

相关文章:

node.js - Sequelize DataTypes 类型错误 : Cannot read property 'INTEGER' of undefined

javascript - 为什么 "RangeError: Invalid status code: 0",firebase 函数

node.js - 在 firebase 中看不到请求 header 的值?

javascript - Firebase Web 注销不会发送任何 XHR

firebase - Firestore (NoSQL) 是社交媒体应用程序的不错选择吗?

ios - 无法完成提交 dSYM 当结构到 firebase 迁移以进行 crashlytics

node.js - 处理ExpressJS中混合的同步和异步错误的最佳方法

node.js - 无法将 firebase 函数迁移到 Node 10 运行时

javascript - 使用 Express session 设置域会阻止保存 cookie

Node.js 应用程序无法在 Cloud Functions for Firebase 中渲染 hbs