node.js - 如何使用主体解析器读取 Express.js 中的 BSON 数据

标签 node.js http express bson body-parser

我有一个 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/

相关文章:

javascript - 解决带有嵌套 promise 的对象的美丽方法?

angularjs - Jade 中的 Angular ng-include。

javascript - MySql、NodeJS、ExpressJS 和 bcrypt : what is the best way to handle users' login?

java - 线程等待一组异步任务完成

javascript - 是否可以在 AJAX 调用中使用条件来避免重复代码?

javascript - Node 中的 req.body 是什么?

node.js - 无法删除 json 元素

javascript - Node js后端调用python函数

javascript - FIREBASE admin sdk 不返回 promise ? Node JS

javascript - 如何修复此错误 : [$sce:itype] in AngularJS 1. 6?