使用Busboy将Node.js中的JTIpart / form-data转换为JSON

时间:2017-12-29 08:32:24

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

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

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()

2 个答案:

答案 0 :(得分:2)

您必须按照文档示例中的说明调用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);

});

答案 1 :(得分:0)

享受这个简单的快速中间件,它将所有 Content-Type: multipart/form-data 转换为 json 格式的 req.body :)

const Busboy = require('busboy');

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

  busboy.on(
    "field",
    (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
      formData = { ...formData, [fieldname]: val };
    },
  );

  busboy.on("finish", () => {
    req.body = formData;
    next();
  });

  req.pipe(busboy);
};