我正在为我的 Laravel 应用程序进行 Ajax 登录。
我正在使用 Angular:
$http({
method: 'POST',
url: '/admin/login',
headers: {
'Content-Type': 'application/json'
},
data: {email:$scope.email,password:$scope.password}
})
这个请求工作正常,我的问题是 Laravel 的响应总是重定向我,因为它应该 如果我没有发送 JSON:
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
这就是 Laravel 框架代码。它不断将我重定向回来,但我想触发条件
if ($request->expectsJson())
并获得 JSON 响应而不是重定向。
为了触发该条件,我缺少什么?
我还补充道:
headers: {
'Content-Type': 'application/json','X-Requested-With' :'XMLHttpRequest'
}
还是不行。
public function expectsJson()
{
return ($this->ajax() && ! $this->pjax()) || $this->wantsJson();
}
我的标题:
接受:application/json、text/plain、/
接受编码:gzip、deflate
接受语言:en-US,en;q=0.8
连接:保持活动状态
内容长度:57
内容类型:application/json
X-请求-With:XMLHttpRequest
出于安全原因,我没有包含令牌/cookie 和原始 url,但它们就在那里。
编辑:我尝试清除 artisan 缓存,但仍然没有任何结果。
php artisan cache:clear
还有
composer dump-autoload
只需在 laravel 10 中使用
$request->isJson()
代替 'Content-type': 'application/json'