How to read BSON data in Express.js with body parser
我有一个 Node.js API,它使用 Express.js 和 body 解析器,它从 python 客户端接收 BSON 二进制文件。
Python 客户端代码:
|
1
2 3 4 5 6 |
data = bson.BSON.encode({
“some_meta_data”: 12, “binary_data”: binary_data }) headers = {‘content-type’: ‘application/octet-stream’} response = requests.put(endpoint_url, headers=headers, data=data) |
现在我的 Node.js API 中有一个端点,我想在其中反序列化 BSON 数据,如文档中所述:https://www.npmjs.com/package/bson。我正在努力的是如何从请求中获取二进制 BSON 文件。
这里是 API 端点:
|
1
2 3 4 5 6 |
exports.updateBinary = function(req, res){
// How to get the binary data which bson deserializes from the req? let bson = new BSON(); let data = bson.deserialize(???); … } |
你会想要使用 https://www.npmjs.com/package/raw-body 来获取正文的原始内容。
然后将Buffer对象传递给bson.deserialize(..)。下面的快速脏示例:
|
1
2 3 4 5 6 7 8 |
const getRawBody = require(“raw-body”);
app.use(async (req, res, next) => { |
然后只需执行以下操作:
|
1
2 3 |
exports.updateBinary = (req, res) => {
const data = new BSON().deserialize(req.body) } |
- 酷的东西。奇迹般有效!
你也可以使用 body-parser 包:
|
1
2 3 4 5 6 7 8 9 |
const bodyParser = require(‘body-parser’)
app.use(bodyParser.raw({type: ‘application/octet-stream’, limit : ‘100kb’})) app.use((req, res, next) => { |
来源:https://www.codenong.com/52672810/
