Post 请求错误 - Ruby 和 HTTParty

Post Request Errors - Ruby and HTTParty

我正在尝试使用 ruby 和 httparty gem 发出一个简单的 post 请求,但我一直收到 401(未授权)或 500(内部服务器)响应。我已经成功地在 Chrome 扩展 - DHC(Dev Http 客户端)上测试了请求,它始终如一地 returns 200 个响应。

我的脚本:

require "json"
require "httparty"

file = JSON.parse File.read('file.json')

response = HTTParty.post("https://api.placeholder/uri", {
  :body => file,
  :headers => { "Content-Type" => "application/json", "Accept" => "application/json", "Authorization" => "token example-placeholder-token" }
})

puts response.body
puts response.code
puts response.message

返回的两个错误是:

➜  directory  ruby file.rb
{"valid":false}
401
Unauthorized
➜  directory  ruby file.rb
{"valid":false}
500
Internal Server Error

为更简单的 post 请求调试,你必须小心 sending/receiving json 和 ruby(你可以 运行 陷入麻烦ajax 也使用 html 时的方法)。所以给它尽可能多的 "agnostic" 文件格式——文本(或字符串)和最通用的 key/value 对格式要容易得多,我认为是这样的:application/x-www-form-urlencoded

这最终在控制台中给了我一个有效的 200 响应(n.b。不是我最初的请求,因为有点复杂 - 但仍然 "proof of concept"):

require "json"
require "httparty"

response = HTTParty.post("https://api.placeholder-uri",
  {
  :body => { :user => "placehodler-username", :password => "placeholder-password" }.to_json,
  :headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded" }
  })  

puts response.body
puts response.code
puts response.message

感谢 ajax 教程:https://www.airpair.com/js/jquery-ajax-post-tutorial 提供解决此问题的线索。