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

编程入门 行业动态 更新时间:2024-10-28 19:29:19
本文介绍了在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

本文发布于:2023-10-09 21:16:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   数据   Functions   Cloud   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!