【问题标题】:Send Array in post request using node.js using application/x-www-form-urlencoded使用 node.js 使用 application/x-www-form-urlencoded 在 post 请求中发送数组
【发布时间】:2015-04-01 06:55:44
【问题描述】:

我尝试向 API 发送 post 请求,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}]

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

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

【问题讨论】:

  • 你试过了吗:'amounts': [ 15, 30 ]
  • 是的......它将被视为对象......它不起作用

标签: javascript node.js post express


【解决方案1】:

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

amounts=15&amounts=30

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

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2018-03-24
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多