在Cloud Functions中使用Express处理多部分/表单数据POST [英] Handling multipart/form-data POST with Express in Cloud Functions

查看:140
本文介绍了在Cloud Functions中使用Express处理多部分/表单数据POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用Firebase功能和Express处理POST(多部分/表单数据),但是它不起作用。在本地服务器上进行了尝试,效果很好。

I've been trying to handle POSTs (multipart/form-data) with a Firebase function and Express but it just doesn't work. Tried this in local server and it works just fine. Everything's the same except it's not contained in a Firebase function.

除了搞乱请求对象外,似乎还搞砸了服务生的工作方式。

Besides screwing up the request object it seems it also screws up the way busboy works.

我尝试了提出的不同解决方案此处,但它们只是不起作用。正如一个用户提到的那样,永远不会调用传递给busboy的回调(在找到字段或完成对数据的访问时调用),而函数只会挂起。

I've tried different solutions presented here but they just don't work. As one user mentions, the callbacks passed to busboy (to be called when a 'field' is found or when it finishes going through the data) are never called and the function just hangs.

有什么想法吗?

这是我的函数引用代码:

Here's my function's code for reference:

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
}


推荐答案

请阅读用于处理分段上传的文档


...如果您想让Cloud Function处理多部分/表单数据,则可以使用请求的rawBody属性。

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

由于Cloud Functions 预处理某些请求的方式,您可以预期某些Express中间件将无法工作,这就是您遇到的问题。

Because of the way Cloud Functions pre-processes some requests, you can expect that some Express middleware will not work, and that's what you're running into.

这篇关于在Cloud Functions中使用Express处理多部分/表单数据POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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