node.js - 如何将缓冲图像作为 JSON 发送到另一个 API?
问题描述
我正在将数据从网页发送到我设计的另一个 API,该 API 将以 JSON 形式接收它。这个网页有一个表单,表单数据有 2 个图像和一些文本数据。我所做的是使用 Multer 缓冲图像,并将原始 req.body.userImage 重新分配给缓冲图像。另一端的 API 将接收整个 req.body 作为 JSON 并将其保存到 MongoDB 数据库中。由于“userPicture”数据类型是缓冲区,所以我在这里缓冲了使用表单上传的图像,现在我正在尝试将其发送到该 API。但是无法发送缓冲的图像,因为它是一个 Node.js 项目,我使用了 Node.js 的 HTTP 方法,我还使用了 NPM 中的一些其他模块,从它们中我得到了相同的错误代码:413 (有效载荷太大)。我现在如何发送缓冲图像?我是否应该将另一端的 API 设计更改为先接收原始图像,然后再在那里缓冲图像?如果是这种情况,那么我如何将原始图像发送到该 API?
const upload = multer({
limits: {
fileSize: 2000000,
},
fileFilter(req, file, cb) {
if (!file.originalname.match(/\.(jpg|png|jpeg|svg)$/)) {
return cb(new Error("Please upload an image"));
}
cb(undefined, true); //means go ahead and accept the given upload
},
});
app.post("/postData", upload.any('photos'), async (req, res) => {
console.log('data send here')
// console.log(req.body)
// console.log(req.body.name)
// console.log(req.files[0].buffer)
let distroLogo = await sharp(req.files[0].buffer)
.resize({
width: 300,
height: 300
})
.png()
.toBuffer();
req.body.logo = distroLogo
let userPicture = await sharp(req.files[1].buffer)
.resize({
width: 300,
height: 300
})
.png()
.toBuffer();
req.body.userProfilePicture = userPicture
const data = JSON.stringify(req.body)
const options = {
hostname: '***API ADDRESS***',
port: 443,
path: '/**PATH**',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const reque = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
reque.on('data', (d) => {
process.stdout.write(d)
})
})
reque.on('error', (error) => {
console.error(error)
})
reque.write(data)
reque.end()
}), (error, req, res, next) => {
res.status(400).send({
error: error.message
})
}
解决方案
我通过使用 bodyParsers 限制和扩展选项解决了这个问题,这意味着我使用以下代码来增加 bodyParser 的限制以获取超过默认值的值。
添加代码:
app.use(bodyParser.json({
limit: "50mb"
}));
app.use(bodyParser.urlencoded({
limit: "50mb",
extended: true,
parameterLimit: 50000
}));
我使用以下帖子来解决我的问题:
推荐阅读
- javascript - 创建 CSV 时遇到问题,分隔符
- excel - 为什么 VBA 读取我的 ElseIf 语句但不执行它下面的代码?
- windows - 在 Windows 中如何编码 unicode 字符串(宽字符串)?UTF-16LE 还是 UTF-16BE?
- aws-amplify - 放大 API 参考
- docker - docker-compose build 时如何从 Dockerfile 连接到其他容器
- autodesk-forge - Forge Viewer Extension for Toolbar:如何添加自定义组合框
- hangouts-chat - 环聊聊天机器人“来电者没有权限”,PERMISSION_DENIED
- c# - C#适用于linux?
- php - 如何使用 RPC 生成钱包和检索比特币钱包
- python - 在我们之前设置 request.session