【发布时间】:2016-04-22 14:45:18
【问题描述】:
我正在通过 HttpParty 对象向我的 rails API 发送请求:
HTTParty.get(task_list_url(@hotel_id),
:headers => { 'X-User-Email' => @user_email, 'X-User-Token'=> @user_token, 'Content-Type' => 'application/json' }
)
我将此对象存储在@response 变量中
API 上的方法看起来像这样
def index
@tasks = policy_scope(Task).where(hotel: @hotel)
if current_user.created_account == @hotel.account || current_user.hotels.include?(@hotel)
render json: {tasks: @tasks, hotel: @hotel}
else
render json: {
:status => :unauthorized,
:message => "unauthorized"
}
end
end
问题是在 else 情况下,@response 返回的看起来像这样:
#<HTTParty::Response:0x7fbb0a580198 parsed_response={"status"=>"unauthorized", "message"=>"unauthorized"}, @response=#<Net::HTTPOK 200 OK readbody=true>, @headers={"x-frame-options"=>["SAMEORIGIN"], "x-xss-protection"=>["1; mode=block"], "x-content-type-options"=>["nosniff"], "access-control-allow-origin"=>["*"], "access-control-allow-methods"=>["POST, GET, PUT, DELETE, OPTIONS"], "access-control-allow-headers"=>["Origin, Content-Type, Accept, Authorization, Token"], "access-control-max-age"=>["1728000"], "content-type"=>["application/json; charset=utf-8"], "etag"=>["W/\"2cd59ce00f09c29553693183e9a04a4d\""], "cache-control"=>["max-age=0, private, must-revalidate"], "x-request-id"=>["5acc353c-48aa-410d-a4bc-888c653cae02"], "x-runtime"=>["0.459027"], "vary"=>["Origin"], "connection"=>["close"], "transfer-encoding"=>["chunked"]}>
如您所见,相关信息不在@response 中,而是在parsed_response 中。这会在我的客户端应用程序中产生问题,因为我正在检查返回 OK 200 的 @response,而正确的返回应该是 UNAUTHORIZED 401。
如何将正确的 json 响应放入 @response 对象中,或者如果不可能,如何检查 HTTParty 对象中的 parsed_response。
【问题讨论】:
标签: ruby-on-rails json httparty