Laravel $request->expectsJson()

ⅰ亾dé卋堺 提交于 2020-05-13 06:55:32

问题


I am doing an Ajax login for my Laravel application.

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:

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.

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.

expectsJson():

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

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

Edit: I tried clearing the artisan cache and still nothing.

php artisan cache:clear

Also

composer dump-autoload


回答1:


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



来源:https://stackoverflow.com/questions/45015586/laravel-request-expectsjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!