我有一个Node.js API使用Express.js与body解析器从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中有一个端点,我想按照文档:https://www.npmjs.com/package/bson中的说明对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抓住身体的原始内容。
然后将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)
}
你也可以使用body-parser包:
const bodyParser = require('body-parser')
app.use(bodyParser.raw({type: 'application/octet-stream', limit : '100kb'}))
app.use((req, res, next) => {
if (Buffer.isBuffer(req.body)) {
req.body = JSON.parse(req.body)
}
})