Laravel $request->expectsJson()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45015586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel $request->expectsJson()
提问by Summer Developer
I am doing an Ajax login for my Laravel application.
我正在为我的 Laravel 应用程序进行 Ajax 登录。
I am using Angular:
我正在使用角:
$http({
method: 'POST',
url: '/admin/login',
headers: {
'Content-Type': 'application/json'
},
data: {email:$scope.email,password:$scope.password}
})
This request works fine, my problem is that Laravel's response always redirects me, as it should if I wasn't sending JSON:
这个请求工作正常,我的问题是 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);
}
That is the Laravel framework code. It keeps redirected me back, but I want to fire the conditional if ($request->expectsJson())
and get a JSON response rather than a redirect.
那就是 Laravel 框架代码。它一直将我重定向回来,但我想触发条件if ($request->expectsJson())
并获得 JSON 响应而不是重定向。
What am I missing in order to trigger that conditional?
为了触发条件,我缺少什么?
I even added:
我什至补充说:
headers: {
'Content-Type': 'application/json','X-Requested-With' :'XMLHttpRequest'
}
And it still won't work.
它仍然不起作用。
public function expectsJson()
{
return ($this->ajax() && ! $this->pjax()) || $this->wantsJson();
}
My headers:
我的标题:
Accept:application/json, text/plain, /
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:57
Content-Type:application/json
X-Requested-With:XMLHttpRequest
接受:应用程序/json,文本/纯文本,/
接受编码:gzip,放气
接受语言:en-US,en;q=0.8
连接:保持连接
内容长度:57
内容类型:应用程序/json
X-Requested-With:XMLHttpRequest
I'm not included tokens/cookies and the origin url for security reason, but they are in there.
出于安全原因,我没有包含令牌/cookies 和原始 url,但它们在那里。
Edit: I tried clearing the artisan cache and still nothing.
编辑:我尝试清除工匠缓存,但仍然没有。
php artisan cache:clear
php artisan cache:clear
Also
还
composer dump-autoload
composer dump-autoload
回答by 4givN
You should use Accept
key not Content/type
. For more details, check this github discussion
您应该使用Accept
key not Content/type
。有关更多详细信息,请查看此 github 讨论