首页 > 解决方案 > 如何使用grape-api解码GET请求中的编码查询参数

问题描述

我正在使用grape-api ,并且在使用编码查询参数从我的前端服务发出GET请求时遇到问题。这就是我的端点设置为接收参数的方式:

params do
  requires :event_id, type: String, desc: 'Event id'
  requires :tickets, type: Array, desc: 'Array of each ticket data ex:  [ {id: "", count: 1 , coupon_code: ""} ]', allow_blank: false do
    requires :id, type: String, desc: 'Ticket id'
    requires :count, type: Integer, desc: 'Number of tickets to get'
    optional :coupon_code, type: String, desc: 'Promocode to apply if any'
  end
end

如您所见,我期待一个event_id参数和另一个对象数组 param ticket,这就是请求 URL 的样子:

http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[]=%7B%22id%22:%22vohd3y3n25cdgbvi3uzmqhcyie3zi53a%22,%22count%22:2%7D

但是,grape 似乎不理解这些编码的查询参数,我得到了这个异常:

[Exception: event_id is missing, tickets[0][id] is missing, tickets[0][id] is invalid, tickets[0][count] is missing, tickets[0][count] is invalid]

我的问题是:有没有办法告诉葡萄正确解码和解析查询参数?我在这里错过了什么吗?

标签: ruby-on-railsrubyrackgrapegrape-api

解决方案


http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[]=%7B%22id%22:%22vohd3y3n25cdgbvi3uzmqhcyie3zi53a%22,%22count%22:2%7D

对于上面的请求 URL,发送的参数名称是eventID而 Grape API requires/expects event_id。此外,ticketsURL 查询字符串参数构造是错误的。

你可以试试这个——http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[0][id] =12&tickets[0][count] =13&tickets[0][coupon_code]=amrrbakry


推荐阅读