gpt4 book ai didi

arrays - 通过 requestJS 发送 JSON 对象和图像文件数组的 POST 请求

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:18 33 4
gpt4 key购买 nike

我正在使用 NODEjs 构建 REST API,使用 Express 路由器和 Multer 中间件来处理多个正文数据和文件。

我的端点路由 127.0.0.1/api/postData 需要:带有字段的 json 数据,其中之一是 json 对象数组(我有嵌套的 Mongoose 模式)和 2 个命名图像 (png/jpg)。

我需要通过 cURL 发送具有以下 5 个对象数据结构的 Post 请求:

name  String
description String
usersArray Array of json objects like: [{"id": "123"}, {"id": "456}]
imgIcon Png/Image providing /path/to/imageIcon.png
imgHeader Png/Image providing /path/to/imageHeader.png

知道如何在 request.js Node http 请求库的帮助下编写此请求吗?

最佳答案

尝试以下操作:

request.post({
url:'http://127.0.0.1:7777/api/postData'
, formData: formData
, qsStringifyOptions : {
arrayFormat : 'brackets' // [indices(default)|brackets|repeat]
}
}, function (err, httpResponse, body) {
// do something...
}

我在 https://www.npmjs.com/package/qs 中找到了 arrayFormat 的三个选项(由 https://www.npmjs.com/package/request 使用):

'indices' sends in postbody: (this is the default case)
usersArray%5B0%5D%5Bid%5D=a667cc8f&usersArray%5B1%5D%5Bid%5D=7c7960fb
decoded:
usersArray[0][id]=a667cc8f&usersArray[1][id]=7c7960fb

'brackets' sends in postbody:
usersArray%5B%5D%5Bid%5D=a667cc8f&usersArray%5B%5D%5Bid%5D=7c7960fb
decoded:
usersArray[][id]=a667cc8f&usersArray[][id]=7c7960fb

'repeat' sends in postbody:
usersArray%5Bid%5D=a667cc8f&usersArray%5Bid%5D=7c7960fb
decoded:
usersArray[id]=a667cc8f&usersArray[id]=7c7960fb

这是在发布之前序列化数组的三种不同方法。基本上这取决于接收端如何需要/可以格式化这些内容。就我而言,使用“括号”很有帮助

关于arrays - 通过 requestJS 发送 JSON 对象和图像文件数组的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31538478/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com