在带有 typhoeus 的 Rails 应用程序中将哈希数组作为参数传递给 POST 的问题

kha*_*hal 3 arrays hash json ruby-on-rails typhoeus

我有两个导轨服务。一个服务于 UI 和一些基本功能 (UIService),另一个管理底层模型和数据库交互 (MainService)。

在 UIService 中,我有一个表单,它收集项目列表并使用它通过 jQuery POST 到 MainService。

我首先使用 javascript 数组并调用 jQuery.post 到 UIService,就像这样 -

var selected_items = new Array();
// Filled up via the form...
params={"name":$("#name_input").val(),
        "items": selected_items };
jQuery.post("/items", params);
Run Code Online (Sandbox Code Playgroud)

然后将其转换为带有键“item_id”的散列数组,然后通过 Typhoeus 像这样转发到 MainService -

items = []
item = {}
params[:items].each do |i|
  item[:item_id] = i
end
## Gives me this ---> items = [ {item_id: 189}, {item_id: 187} ]

req = Typhoeus::Request.new("#{my_url}/items/", 
                            method: :POST, 
                            headers: {"Accepts" => "application/json"})
hydra = Typhoeus::Hydra.new
hydra.queue(req)
hydra.run
Run Code Online (Sandbox Code Playgroud)

在 MainService 中,我需要采用特定格式的 JSON 模式。基本上是一系列项目......像这样 -

{ "name": "test_items", "items": [ {"item_id":"189"},{"item_id": "187"} ] }
Run Code Online (Sandbox Code Playgroud)

问题是,当我从 jQuery 收集数组并将其传递给 UIService 时,它​​在参数中看起来像这样 -

[ {item_id: 189}, {item_id: 187} ]
Run Code Online (Sandbox Code Playgroud)

但是,当它到达 MainService 时,它​​变成了这样——

{"name"=>"test_items",
 "items"=>{"0"=>{"item_id"=>"189"}, "1"=>{"item_id"=>"187"}}
Run Code Online (Sandbox Code Playgroud)

所以,我需要用“item_id”键入项目数组并插入到参数中。我尝试了几种方法将其保留为散列数组,但在目的地总是以错误的格式结束。

我尝试了各种解决方法,比如字符串化,而不是字符串化,构建我自己的哈希数组等等。我在这一点上很卡住了。有任何想法吗?我做错了什么或没有做什么?我可以让它在其他 JSON 模式下工作,但我需要坚持这个模式。

kha*_*hal 5

问题在于我将参数传递给 typhoeus 的方式

之前(有问题)——

req = Typhoeus::Request.new("#{Rails.application.config.custom_ads_url}/groups", 
                            method: :POST,
                            params: parameters,
                            headers: {"Content-Type" => "application/json",     "AUTHORIZATION" => "auth_token #{user.auth_token}"})
Run Code Online (Sandbox Code Playgroud)

after (works) - 请注意,我需要转换为 json 并将其放入正文中。typhoeus 中的 'params' 被视为自定义哈希。

req = Typhoeus::Request.new("#{Rails.application.config.custom_ads_url}/groups", 
                            method: :POST,
                            body: parameters.to_json,
                            headers: {"Content-Type" => "application/json", "AUTHORIZATION" => "auth_token #{user.auth_token}"})
Run Code Online (Sandbox Code Playgroud)