我有一个 Node.js API,使用带有主体解析器的 Express.js,它从 python 客户端接收 BSON 二进制文件。
Python 客户端代码:
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 端点:
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获取 body 的原始内容。
然后传递Buffer
对象到 bson.deserialize(..)
。下面是快速脏示例:
const getRawBody = require("raw-body");
app.use(async (req, res, next) => {
if (req.headers["content-type"] === "application/octet-stream") {
req.body = await getRawBody(req)
}
next()
})
然后只需执行以下操作:
exports.updateBinary = (req, res) => {
const data = new BSON().deserialize(req.body)
}
关于node.js - 如何使用主体解析器读取 Express.js 中的 BSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672810/