POST中的nodejs/express和二进制数据

2g32fytz  于 2023-06-22  发布在  Node.js
关注(0)|答案(4)|浏览(164)

我正在尝试将二进制数据发送到Express应用程序。它工作正常,只要我的值小于0x 80。如果单个值为0x 80或更大,则会扰乱整个缓冲区。
快递经办人:

binary = require('binary');

exports.api = function(req, res){
    var body = req.body.name;
    var buf = new Buffer(body,'binary');

    console.log('body',req.body);
    console.log('req body len', body.length);
    console.log('buf len', buf.length);

    var g = binary.parse(buf)
        .word16bu('a') // unsigned 16-bit big-endian value
        .word16bu('b').vars

    console.log('g.a', g.a);
    console.log('g.b', g.b);

  res.send("respond with a resource");
};

Python客户端(内容类型:application/x-www-form-urlencoded):

import requests
from struct import pack
# send two unsigned shorts (16-bits each).
requests.post('http://localhost:3000/api', data={'name':pack('!HH',1,2)})

当data = 1,2时表示输出。这是我所期望的

body { name: '\u0000\u0001\u0000\u0002' }
req body len 4
buf len 4
g.a 1
g.b 2
POST /api 200 1ms - 23b

当数据= 1,0xFF时表示输出。有趣的是,9520实际上是十六进制的0x 25 0x 30,对应于ASCII中的“%0”。是的,它似乎正在分析“%00%01...”字符串。”””我希望我知道如何阻止它!!!**

body { name: '%00%01%00%FF' }
req body len 12
buf len 12
g.a 9520
g.b 12325
POST /api 200 2ms - 23b
eulz3vhy

eulz3vhy1#

在纠结了很久之后,我想出了这个解决方案:

var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require('path');

app.use(bodyParser.raw({type: 'application/octet-stream', limit : '2mb'}))

app.post('/nist-ws/rest/v1/nist/', function(req, res) {
    var filePath = path.join(__dirname, 'nist_received', `/${Date.now()}.nist`)
    fs.open(filePath, 'w', function(err, fd) {  
        fs.write(fd, req.body, 0, req.body.length, null, function(err) {
            if (err) throw 'error writing file: ' + err;
            fs.close(fd, function() {
                console.log('wrote the file successfully');
                res.status(200).end();
            });
        });
    });
});

bodyParser.raw用Buffer填充req.body,其余代码来自:https://stackabuse.com/writing-to-files-in-node-js/

g6ll5ycj

g6ll5ycj2#

原来是编码问题。一切似乎都默认为'utf8',但在这种情况下,它需要设置为'binary'。
例如:

var buf = new Buffer(body.toString('binary'),'binary');

同样重要的是,我需要将nodejs多方解析器的编码设置为'binary'。参见:https://github.com/superjoe30/node-multiparty/issues/37

nfzehxib

nfzehxib3#

一个现代的Typescript安全方式可能看起来像这样:

export async function readBodyAsBuffer(req: any): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    let buffer = Buffer.alloc(0)
    req.setEncoding(null)
    req.on(
      "data",
      (chunk: string) => (buffer = Buffer.concat([buffer, Buffer.from(chunk)]))
    )
    req.on("end", () => resolve(buffer))
    req.on("error", reject)
  })
}

现在你可以简单地像这样将body作为Buffer:

let buffer = await readBodyAsBuffer(req)
3npbholx

3npbholx4#

与@Holtwick类似,以下是我使用的:

const readBodyAsBuffer = (req: express.Request): Promise<Buffer> => {
  return new Promise((resolve, reject) => {
    let body: Buffer[] = []
    req.on('data', chunk => {
      body.push(chunk)
    })
    req.on('end', () => {
      resolve(Buffer.concat(body))
    })
    req.on('error', err => {
      reject(err)
    })
  })
}

用作const buffer = await readBodyAsBuffer(req)

相关问题