我通过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
问题出在其他情况下,@ 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
中看到。这会在我的客户端应用程序中产生问题,因为我正在检查@response,它返回OK 200,而正确的返回应该是UNAUTHORIZED 401.
如何在@response对象中放置正确的json响应,或者如果不可能如何检查HTTParty对象中的parsed_response。
答案 0 :(得分:3)
控制器的这个小修正应该做的事情。
而不是:
render json: {
:status => :unauthorized,
:message => "unauthorized"
}
使用此:
render json: { message: "unauthorized" }, status: :unauthorized