我正在尝试将二进制数据发送到快速应用程序.只要我的值小于 0x80,它就可以正常工作.如果单个值是 0x80 或更大,它会弄乱整个缓冲区.
I'm trying to send binary data to an express app. It works fine, as long as my values are smaller than 0x80. If a single value is 0x80 or greater, it messes up the whole buffer.
快递处理程序:
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):
Python client (Content-Type: application/x-www-form-urlencoded):
import requests from struct import pack # send two unsigned shorts (16-bits each). requests.post('localhost:3000/api', data={'name':pack('!HH',1,2)})当数据 = 1,2 时表示输出.这是我所期望的.
Express output when data = 1,2. This is what I'd expect.
body { name: 'u0000u0001u0000u0002' } req body len 4 buf len 4 g.a 1 g.b 2 POST /api 200 1ms - 23b当数据 = 1,0xFF 时表示输出.有趣的是,9520实际上是十六进制的0x25 0x30,对应ASCII中的%0".是的,它似乎正在解析 '%00%01...' 字符串.我希望我知道如何防止这种情况发生!!!
Express output when data = 1,0xFF. It's interesting to note that 9520 is actually 0x25 0x30 in hex, which corresponds to "%0" in ASCII. Yes, it appears to be parsing the '%00%01...' string. I wish I knew how to prevent this!!!
body { name: '%00%01%00%FF' } req body len 12 buf len 12 g.a 9520 g.b 12325 POST /api 200 2ms - 23b 推荐答案原来是编码问题.一切似乎都默认为utf8",但在这种情况下,它需要设置为二进制".
It turned out to be an encoding issue. Everything seems to default to 'utf8', but in this case it needs to be set to 'binary'.
例如:
var buf = new Buffer(body.toString('binary'),'binary');同样重要的是,我需要将 nodejs 多方解析器的编码设置为二进制".参见:github/superjoe30/node-multiparty/issues/37
Equally as important, I needed to set nodejs multiparty parser's encoding to 'binary'. See: github/superjoe30/node-multiparty/issues/37
更多推荐
POST 中的 nodejs/express 和二进制数据
发布评论