Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel $request->expectsJson()

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

like image 538
Summer Developer Avatar asked Jul 10 '17 15:07

Summer Developer


People also ask

What is request -> expectsJson ()?

Laravel Request: expectsJson() This function determines if current request expects a json response.

How can you retrieve the full URL for the incoming request laravel?

The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method.

What is illuminate HTTP request in laravel?

Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application as well as retrieve the input, cookies, and files that were submitted with the request.


1 Answers

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

enter image description here

like image 122
4givN Avatar answered Sep 28 '22 04:09

4givN