使用 application/x-www-form-urlencoded 使用 node.js 在 post 请求中发送数组

Send Array in post request using node.js using application/x-www-form-urlencoded

我尝试发送 post 请求到 API 并且 post 参数应该是数组, 这是在 cURL

中发送的方法
curl http://localhost:3000/check_amounts
  -d amounts[]=15 \
  -d amounts[]=30

我尝试在 Node.js 中使用请求模块

request.post('http://localhost:3000/check_amounts', {
        form: { 
                'amounts[]': 15 ,
                'amounts[]': 30
              }
    }, function(error, response, body) {
        console.log(body)
        res.json(body);
    });

但是第二个数量覆盖了第一个数量,API 得到如下结果:amounts = [30]

然后我尝试用不同的方式发送它

 request.post('http://localhost:3000/check_amounts', {
            form: { 
                    'amounts[]': [ 15 , 30]
                  }
        }, function(error, response, body) {
            console.log(body)
            res.json(body);
        });

但结果不如预期amounts = [{"0":15},{"1":30}]

注意:header 应该包含 'Content-Type':'application/x-www-form-urlencoded' 而不是 'application/json'

有人解决这个问题吗?

阅读请求手册就很容易了。您应该做的就是将表格替换为 querystring 而不是 object,在您的情况下,这应该是:

amounts=15&amounts=30

我唯一不确定的是上述表达式在您的网络服务器中是否有效。据我所知,它在 java struts 中运行良好。所以如果不是你可以试试 amounts[]=15&amounts[]=30 代替。希望对你有帮助。