2017-04-24 87 views
0

我嘗試在我的Laravel + Vue SPA中實施JWT Auth。Laravel with JWT Auth:獲取狀態碼錯誤消息

在我的控制器我檢查喜歡

try { 
     if (!$token = JWTAuth::attempt($credentials)) { 
      return response()->json(
       [ 
        'error' => 'Invalid Credentials', 
       ], 401 
      ); 
     } 
    } catch (JWTException $e) { 
     return response()->json(
      [ 
       'error' => 'Could not create token!', 
      ] 
     ); 
    } 

    return response()->json(
     [ 
      'token' => $token, 
     ] 
    ); 

我的API調用這個樣子的憑據:

axios.post('/api/user/signin', payload) 
    .then((res) => { 
     console.log(res) 
    }) 
    .catch((err) => { 
     console.log(err) 
    }) 

如果我通過有效憑證與​​我得到的then塊令牌和可以在控制檯中記錄這一點。

如果我通過無效的憑據我在控制檯得到一個錯誤:

Error: Request failed with status code 401 at createError (app.js:10562) at settle (app.js:21378) at XMLHttpRequest.handleLoad (app.js:10401)

我怎樣才能得到錯誤「無效憑證」?如果我從響應中刪除狀態碼或將其設置爲200,則會出現「無效憑證」錯誤。

Error with Status

回答

1

您可以使用錯誤的response關鍵。獲得迴應。

axios.post('/api/user/signin', payload) 
    .then((res) => { 
     console.log(res) 
    }) 
    .catch((err) => { 
     console.log(err.response) 
    }) 

入住這裏:https://github.com/mzabriskie/axios/blob/master/UPGRADE_GUIDE.md#012x---0130

+0

哦,我感覺很愚蠢,現在...我想,既然錯誤是作爲一個字符串輸出,沒有對象......謝謝你許多! – Sebastian

+1

哈哈,發生! :d –