2016-04-22 63 views
1

我通過HttpParty對象發送到我的軌道API的請求:JSON響應使用HTTPPARTy總是返回200

HTTParty.get(task_list_url(@hotel_id), 
     :headers => { 'X-User-Email' => @user_email, 'X-User-Token'=> @user_token, 'Content-Type' => 'application/json' } 
    ) 

我這個對象存儲在@應答變量

對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 

的問題在其他情況下,返回@應答看起來就像是:

#<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進行檢查。

回答

3

這個小小的控制器應該做的事情。

相反的:

render json: { 
    :status => :unauthorized, 
    :message => "unauthorized" 
    } 

使用此:

render json: { message: "unauthorized" }, status: :unauthorized 
相關問題