如何使用正文解析器读取Express.js中的BSON数据

时间:2018-10-05 20:20:54

标签: node.js http express bson body-parser

我有一个将Express.js与主体解析器结合使用的Node.js API,该主体解析器从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(???);
    ...
}

2 个答案:

答案 0 :(得分:3)

您将要使用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)
}

答案 1 :(得分:0)

您也可以使用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)
    }
})
相关问题