Laravel $ request-> expectsJson() [英] Laravel $request->expectsJson()

查看:1004
本文介绍了Laravel $ request-> expectsJson()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Laravel应用程序进行Ajax登录.

I am doing an Ajax login for my Laravel application.

我正在使用Angular:

I am using Angular:

$http({
  method: 'POST',
  url: '/admin/login',
  headers: {
        'Content-Type': 'application/json'
  },
  data: {email:$scope.email,password:$scope.password}
})

此请求工作正常,我的问题是Laravel的响应总是重定向我,因为如果我不发送JSON,它应该

This request works fine, my problem is that Laravel's response always redirects me, as it should if I wasn't sending 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响应而不是重定向.

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.

要触发该条件,我缺少什么?

What am I missing in order to trigger that conditional?

我什至添加了

 headers: {
        'Content-Type': 'application/json','X-Requested-With' :'XMLHttpRequest'
  }

它仍然无法正常工作.

expectsJson() :

public function expectsJson()
    {
        return ($this->ajax() && ! $this->pjax()) || $this->wantsJson();
    }

我的标题:

接受:application/json,文本/纯文本,/

Accept-Encoding:gzip,放气

Accept-Encoding:gzip, deflate

Accept-Language:en-US,en; q = 0.8

Accept-Language:en-US,en;q=0.8

连接:保持活动状态

内容长度:57

Content-Type:application/json

Content-Type:application/json

X-Requested-With:XMLHttpRequest

X-Requested-With:XMLHttpRequest

出于安全原因,我不包含令牌/cookie和原始URL,但是它们在其中.

I'm not included tokens/cookies and the origin url for security reason, but they are in there.

我试图清除手工艺品的缓存,但还是一无所获.

I tried clearing the artisan cache and still nothing.

php artisan cache:clear

composer dump-autoload

推荐答案

您应该使用Accept键而不是Content/type.有关更多详细信息,请检查此github讨论

You should use Accept key not Content/type. For more details, check this github discussion

这篇关于Laravel $ request-> expectsJson()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆