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

Tar*_*lah 1 javascript post node.js express

我试图向API发送post请求,post参数应该是数组,这是如何在cURL中发送它

curl http://localhost:3000/check_amounts
  -d amounts[]=15 \
  -d amounts[]=30
Run Code Online (Sandbox Code Playgroud)

我尝试使用请求模块在Node.js中执行此操作

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

但第二个金额覆盖第一个金额,API获得如下结果: amounts = [30]

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

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

但结果并不像预期的那样 amounts = [{"0":15},{"1":30}]

注意:标题应包含'Content-Type':'application/x-www-form-urlencoded'not'application/json'

有没有人能解决这个问题?

Mik*_*ike 5

如果您阅读请求手册,这很容易.你所要做的就是更换表格,querystring而不是object在你的情况下,这应该是:

amounts=15&amounts=30

我唯一不确定的是上面的表达式在您的Web服务器中有效.据我所知,它在java中运行良好struts.所以,如果没有,你可以尝试 amounts[]=15&amounts[]=30.希望它有所帮助.