我正在使用带有react和axios的laravel 5.8。我建立了一个登录页面,登录失败后出现控制台“错误请求”错误。我从服务器获得了正确的响应,但是我不断收到发布请求的控制台错误。
这是请求:
export const getProfile = () => {
return axios
.get('api/profile', {
headers: { Authorization: `Bearer ${localStorage.usertoken}` }
})
.then(response => {
return response.data
})
.catch(err => {
console.log(err)
})
}
这是UserController的登录功能
public function login(Request $request)
{
$credentials = $request->json()->all();
try {
if (!$token = JWTAuth::attempt($credentials)) {
$loginsCount = 0; //init counter
if ($request->session()->has('userLoginsCount')) {
//get session value
$loginsCount = $request->session()->get('userLoginsCount');
//check login attempts count
if ($loginsCount == 5) {
$current_timestamp = now()->timestamp;
Log::info($current_timestamp.' User exceeded alowed
login attempts : '.$request->ip());
$request->session()->put('userLoginsCount', 0);
return;
} else {
//increment it
$loginsCount++;
// set the new value
$request->session()->put('userLoginsCount',
$loginsCount);
}
} else {
$request->session()->put('userLoginsCount', $loginsCount);
}
//Store session
Session::save();
return response()->json(['error' => 'invalid credentials'],
400);
}
} catch (JWTExecption $e) {
return response()->json(['error' => 'could not create token'], 500);
}
return response()->json(compact('token'));
}
Api路线:
Route::post('register', 'UserController@register');
Route::post('login', 'UserController@login');
Route::get('profile', 'UserController@getAuthenticatedUser');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
网络路由:
Auth::routes();
Route::get( '/{path?}', function(){
return view( 'layouts/app' );
} )->where('path', '.*');
这里有错误图片
答案 0 :(得分:0)
我相信这些是修复所有问题的步骤。
1。将错误响应更改为401(未经授权)。
return response()->json(['error' => 'invalid credentials'], 401);
2。使用前,请从axios错误响应中检索错误消息。
export const getProfile = () => {
return axios
.get('api/profile', {
headers: { Authorization: `Bearer ${localStorage.usertoken}` }
})
.then(response => {
return response.data
})
.catch(err => {
// retrieve the error message
let message = err.response.data.error;
console.log(message);
// now you can do something with 'message'
// ...
})
您正在将整个错误转储到控制台,而不是提取实际消息。对不起,我忽略了这个。