如何使用正文解析器读取 Express.js 中的 BSON 数据
How to read BSON data in Express.js with 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 获取正文的原始内容。
然后将 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)
}
})
我有一个 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 获取正文的原始内容。
然后将 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)
}
})