如何在NodeJS中发送带有多部分/相关数据的HTTP响应

时间:2016-06-08 18:53:31

标签: node.js multipartform-data

我尝试使用多部分/相关数据发送HTTP响应,其中包含一些随机文本数据作为第一部分,二进制数据(DER格式的证书文件)作为第二部分。

从Wireshark看,似乎第一部分是正确的,但第二部分(PKIX)被破坏 - WS显示格式错误的数据包。

我也尝试将数据作为缓冲区发送,但无济于事。

代码是这样的 - 我错过了什么?

var http = require('http');

var server = http.createServer(function(req, res) {    

    var data = 'some data';
    var file = fs.readFileSync("cert.der");

    var responseData = '--abcd1234\r\n' +
                'Content-type: text/xml; charset=utf-8\r\n' + 'Content-Transfer-Encoding: binary\r\n' + 'Content-ID: <xxxx>\r\n\r\n' +
                data + '\r\n' +
                '--abcd1234\r\n' +
                'Content-type: application/pkix-cert\r\n' + 'Content-Transfer-Encoding: binary\r\n' + 'Content-ID: <yyyy>\r\n\r\n';

    res.writeHead(200, "OK", {'Content-Type': 'multipart/related; charset=utf-8; boundary="abcd1234"; type="text/xml"; start="<SOAP-ENV:Envelope>"'});
    res.write(responseData);
res.write(file);
res.end('\n\r--abcd1234--');
});

server.listen(8008);

1 个答案:

答案 0 :(得分:-1)

请参阅下面的NodeJS中的多部分/相关请求示例。此示例显示如何使用JSON和base64编码的二进制数据格式化请求字符串。希望这会有所帮助。

原生NodeJS请求:

var http = require("https");

var options = {
  "method": "POST",
  "hostname": "examplehostname.com",
  "port": null,
  "path": "/path/v1/files",
  "headers": {
    "content-type": "multipart/related; boundary=Example_boundary_123456",
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write("--Example_boundary_123456\nContent-Type: application/json\nContent-Description: json\n \n{\n    \"title\": \"Example Title\",\n    \"description\": \"Exmaple desc......\",\n    \"date\": 2016-08-31\n}\n \n--Example_boundary_123456\nContent-Type: application/pdf\nContent-Transfer-Encoding: base64\nContent-Description: document\n \nVGhlIFBsZWRnZSBvZiBBbGxlZ2lhbmNlIHRvIHRoZSBGbGFnOiCTSSBwbGVkZ2UgYWxsZWdpYW5j\nZSB0byB0aGUgRmxhZyBvZiB0aGUgVW5pdGVkIFN0YXRlcyBvZiBBbWVyaWNhLCBhbmQgdG8gdGhl\nIFJlcHVibGljIGZvciB3aGljaCBpdCBzdGFuZHMsIG9uZSBOYXRpb24gdW5kZXIgR29kLCBpbmRp\ndmlzaWJsZSwgd2l0aCBsaWJlcnR5IGFuZCBqdXN0aWNlIGZvciBhbGwulCwgc2hvdWxkIGJlIHJl\nbmRlcmVkIGJ5IHN0YW5kaW5nIGF0IGF0dGVudGlvbiBmYWNpbmcgdGhlIGZsYWcgd2l0aCB0aGUg\ncmlnaHQgaGFuZCBvdmVyIHRoZSBoZWFydC4gV2hlbiBub3QgaW4gdW5pZm9ybSBtZW4gc2hvdWxk\nIHJlbW92ZSBhbnkgbm9uLXJlbGlnaW91cyBoZWFkZHJlc3Mgd2l0aCB0aGVpciByaWdodCBoYW5k\nIGFuZCBob2xkIGl0IGF0IHRoZSBsZWZ0IHNob3VsZGVyLCB0aGUgaGFuZCBiZWluZyBvdmVyIHRo\nZSBoZWFydC4gUGVyc29ucyBpbiB1bmlmb3JtIHNob3VsZCByZW1haW4gc2lsZW50LCBmYWNlIHRo\nZSBmbGFnLCBhbmQgcmVuZGVyIHRoZSBtaWxpdGFyeSBzYWx1dGUuIE1lbWJlcnMgb2YgdGhlIEFy\nbWVkIEZvcmNlcyBub3QgaW4gdW5pZm9ybSBhbmQgdmV0ZXJhbnMgbWF5IHJlbmRlciB0aGUgbWls\naXRhcnkgc2FsdXRlIGluIHRoZSBtYW5uZXIgcHJvdmlkZWQgZm9yIHBlcnNvbnMgaW4gdW5pZm9y\nbS4=\n \n--Example_boundary_123456");
req.end();