Home 422 (Unprocessable Entity) in Angular to post in laravel login api
Reply: 1

422 (Unprocessable Entity) in Angular to post in laravel login api

Raikumar Khangembam
1#
Raikumar Khangembam Published in 2017-12-07 17:52:20Z

i am trying to login using frontend(angular 4) to larvel auth api then i am getting this error on console log.

422 (Unprocessable Entity)

it looks like sending empty form fields, this is response

{"message":"The given data was invalid.","errors":{"email":["The email field is required."],"password":["The password field is required."]}}

It work fine in postman application for test, i also change content type(application/json and application/x-www-form-urlencoded) on angular code.

the error happens in login, for registration everything work fine.

this is login.components.ts file

<div class="modal-body">
      <form [formGroup]="loginForm">
        <div class="input-group">
          <input type="email" class="form-control loc2" formControlName="email" placeholder="{{ 'LOGIN_DIALOG.EMAIL_PLACEHOLDER' | translate}}" required="">
          <p *ngIf="loginForm.get('email').hasError('validateEMAIL') && (loginForm.get('email').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.EMAIL_INVALID_MSG' | translate}}</p>
        </div>
        <div class="input-group">
          <input type="password" class="form-control loc" formControlName="password" placeholder="{{ 'LOGIN_DIALOG.PASSWORD_PLACEHOLDER' | translate}}" required="">
          <p *ngIf="loginForm.get('password').hasError('minlength') && (loginForm.get('password').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.PASSWORD_INVALID_LEN_MSG' | translate}}</p>
          <p *ngIf="loginForm.get('password').hasError('required') && (loginForm.get('password').touched || formSubmit)" class="value-err show">{{ 'LOGIN_DIALOG.PASSWORD_REQUIRED' | translate}}</p>
        </div>
        <p class="pull-right space10">{{ 'LOGIN_DIALOG.PASSWORD_FORGET' | translate}} </p>
        <div class="form-group">
          <button type="button" (click)="onClickLogin()" class="btn up me">{{ 'LOGIN_DIALOG.LOGIN_BUTTON' | translate}}</button>
        </div>
        <div class="form-group our">
          <input type="checkbox" id="custom_checkbox2">
          <label for="custom_checkbox2">{{ 'LOGIN_DIALOG.REMEMBER_ME' | translate}} </label>
        </div>
      </form>
      <p class="text-center">{{ 'LOGIN_DIALOG.LOGIN_WITH_MSG' | translate}}</p>
    </div>

this is auth.service.ts file for login function

logInUser(signInData) {
    this.http.post(
      'api/login', { signInData }
    ).subscribe((res: Response) => {
      const data = res.json();
      if (data.error == 1) {
       // const message = data.error.user_authentication[0];
        this.toastyService.error(data.message);
      }else if (data.error == 2) {
        // const message = data.error.user_authentication[0];
         this.toastyService.error(data.message.original.message);
       } else {
        this.store.dispatch(this.authActions.loginSuccess(data));
        this.modalShow$.next(false);
        this.toastyService.success('Login Success');
        this.setTokenInLocalStorage(res.headers.toJSON());
      }
    });
  }

this is http.ts, here i changed content type but not working.

 post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
    this.requestInterceptor();
    return super.post(this.getFullUrl(url), body, this.requestOptions(options))
      .catch(this.onCatch.bind(this))
      .do((res: Response) => {
        this.onSubscribeSuccess(res);
      }, (error: any) => {
        this.onSubscribeError(error);
      })
      .finally(() => {
        this.onFinally();
      });
  }

 private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
    if (options == null) {
      options = new RequestOptions();
    }

    if (options.headers == null) {
      const token = localStorage.getItem('accessToken');
      options.headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': token
      });
    }
    return options;
  }

This is laravel loginController class for login function

public function login(Request $request)
    { 
      $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            $user = $this->guard()->user();
            if($user['confirmed'] == 0){
                $response['error'] = 1;
                $response['message'] = "you havn't verified your email..";
                return response()->json($response, 201);
            }else{
                $user->generateToken();
                return response()->json(
                    $user->toArray()
               );
            }

        }
        $res['errors'] = 2;
        $res['message'] = $this->sendFailedLoginResponse($request);
       return response()->json($res, 201);
    }

THis is AuthenticateUser.php file

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;


    public function showLoginForm()
    {
        return view('auth.login');
    }


    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }


    protected function validateLogin(Request $request)
    {

        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }


    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }


    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }


    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }


    protected function authenticated(Request $request, $user)
    {
        //
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        /*
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);*/
        return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
     }
   public function username()
     {
        return 'email';
     }
}

my response is here when giving any invalid input but i havent got this response in frontend but it work in postman application.

{
    "errors": 2,
    "message": {
        "headers": {},
        "original": {
            "success": false,
            "message": "Invalid username or password!"
        },
        "exception": null
    }
}

when i check in laravel debugger i got

The given data was invalid.

I tried related post of 422 error, but not able find solution. Where do i fix this issue?

Rahul Reghunath
2#
Rahul Reghunath Reply to 2017-12-07 18:37:14Z

I think it is not an error. Laravel validator sends validation responses with 422 error code if request type is ajax. Here the message is coming from sendFailedLoginResponse() function in AuthenticatesUsers class and that is looking fine. You can catch the JSON file and display to the page that is "Invalid username or password!". The problem you are getting the same error with correct credentials right? Check config/auth.php file has correct user model name and user model is Authenticatable

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.310324 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO