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

编程入门 行业动态 更新时间:2024-10-24 22:28:21
本文介绍了POST 中的 nodejs/express 和二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将二进制数据发送到快速应用程序.只要我的值小于 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 和二进制数据

本文发布于:2023-10-09 18:10:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二进制数   POST   nodejs   express

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!