node.js - 使用 Busboy 在 Node.js 中将 Multipart/form-data 转换为 JSON

标签 node.js firebase multipartform-data google-cloud-functions busboy

我正在开发一个 ios 应用程序,它使用 mutipart/form-data URLRequest 将图像和文本发送到我的 firebase 服务器。为了处理我的云函数中的数据,我使用documentation中提到的方法。将 mutipart/form-data 解析为 JSON 格式,这是我的代码:

const Busboy = require('busboy');

exports.test = functions.https.onRequest((req, res) => {
    console.log("start");
    console.log(req.rawBody.toString());
    if (req.method === 'POST') {
        var busboy = new Busboy({ headers: req.headers});
        busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
            console.log('field');
        });

        busboy.on('finish', function() {
            console.log('finish');
            res.json({
                data: null,
                error: null
            });
        });

        req.pipe(busboy);
    } else {
        console.log('else...');
    }
});

但是,上面的代码似乎不起作用,这是控制台的输出:

Function execution started
start
--Boundary-43F22E06-B123-4575-A7A3-6C144C213D09
Content-Disposition: form-data; name="json"

{"name":"Alex","age":"24","friends":["John","Tom","Sam"]}
--Boundary-43F22E06-B123-4575-A7A3-6C144C213D09--
finish
Function execution took 517 ms, finished with status code: 200

如您所见,on('field') 函数永远不会执行。我错过了什么?

此外,这里是 swift 中用于发送 httpRequest 的代码:

var request = URLRequest(url: myCloudFunctionURL)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=myBoundary", forHTTPHeaderField: "Content-Type")
request.addValue(userToken, forHTTPHeaderField: "Authorization")
request.httpBody = myHttpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, requestError) in 
    // callback
}.resume()

最佳答案

您必须调用 busboy.end(req.rawBody); 而不是 req.pipe(busboy),如文档示例中所述。我不知道为什么 .pipe 不起作用。调用.end将产生相同的结果,但以不同的方式。

const Busboy = require('busboy');

exports.helloWorld = functions.https.onRequest((req, res) => {

        const busboy = new Busboy({ headers: req.headers });
        let formData = {};

        busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
            // We're just going to capture the form data in a JSON document.
            formData[fieldname] = val;
            console.log('Field [' + fieldname + ']: value: ' + val)
        });

        busboy.on('finish', () => {
            res.send(formData);
        });

        // The raw bytes of the upload will be in req.rawBody.
        busboy.end(req.rawBody);

});

关于node.js - 使用 Busboy 在 Node.js 中将 Multipart/form-data 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48019718/

相关文章:

firebase - 如何在其他计算机上处​​理现有的Firebase(功能)项目?

google-apps-script - UrlFetchApp 在 Google Apps 脚本中上传文件 multipart/form-data

android - retrofit 2 动态设置零件参数名称

javascript - 如何在 javascript/vuejs 中从子 ID 中过滤父 json

node.js - 如何 mapreduce 具有相互关联的复杂子文档的对象

javascript - 无法安装npm?生成应用程序时出现问题

java - MessagingErrorCode 的成员对应什么错误码?

node.js - 如何使用 Mongoose 和 NodeJS 在 MongoDB 中保存嵌套数组

javascript - Firebase 的单元测试 - 文件未包含问题(路由器 404 问题)

ios - 如何扩展 IOS SimpleURLConnections HTTP POST 以发送可由 CGI Perl 解码的说明