2014-11-03 40 views
0

我在我的角碼一個Ajax請求通過我的API在簽約用戶:設置成功和錯誤響應

$http.post(LOGIN, { 
    username: username, 
    password: password 
}).success(function(response){ 
    console.log('response:') 
    console.log(response); 
    console.log('_________') 
}).error(function(response){ 
    console.log('response:') 
    console.log(response); 
    console.log('_________') 
})} 

它完美,除了那response變量。如果觸發成功,則將本地response變量設置爲空字符串(未定義),並且如果觸發該故障,那麼將response變量設置爲空字符串。

這是我得到我的控制檯:

POST http://0.0.0.0:3000/sessions 401 (Unauthorized) 
response: 

_________ 

如果我返回200種狀態:

response: 

_________ 

這裏是我的服務器端Rails代碼:

def login 
    status = :unauthorized 
    status = :ok if User.find_by(username: session_params[:username]).try(:authenticate, session_params[:password]) 
    head status 
end 

在我正在閱讀的書中,我們實際上向用戶顯示了錯誤響應。我應該如何更改我的服務器端代碼,以便用實際消息填充response?還是應該改變我的客戶端代碼?

回答

0

根據$http documentation(部分收益),成功和錯誤接收下一個屬性:

success(function(data, status, headers, config, statusText) {} 

所以你看到,第一個參數是數據和狀態是第二個。你不會返回任何數據。要獲得狀態代碼,您必須執行下一步:

.success(function(data, status){ 
    console.log('response:') 
    console.log(data + ' ' + status); 
    console.log('_________')