Angular 中的 422(不可处理实体)在 Laravel 登录 api 中发布

莱库玛·康根巴姆

我正在尝试使用前端(angular 4)登录到 larvel auth api,然后我在控制台日志中收到此错误。

422 (Unprocessable Entity)

它看起来像发送空表单字段,这是响应

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

在此处输入图片说明

它在邮递员应用程序中运行良好以进行测试,我还在角度代码上更改内容类型(application/json 和 application/x-www-form-urlencoded)。

错误发生在登录时,注册一切正常。

这是 login.components.ts 文件

<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>

这是用于登录功能的 auth.service.ts 文件

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());
      }
    });
  }

这是 http.ts,在这里我更改了内容类型但不起作用。

 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;
  }

这是用于登录功能的 laravel loginController 类

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);
    }

这是 AuthenticateUser.php 文件

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';
     }
}

当给出任何无效输入时,我的回复就在这里,但我没有在前端得到这个回复,但它在邮递员应用程序中工作。

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

当我检查 laravel 调试器时,我得到了

The given data was invalid.

我尝试了 422 错误的相关帖子,但找不到解决方案。我在哪里解决这个问题?

拉胡尔·雷古纳特

我认为这不是错误。如果请求类型为 ajax,Laravel 验证器会发送带有 422 错误代码的验证响应。这里的消息来自 AuthenticatesUsers 类中的 sendFailedLoginResponse() 函数,看起来不错。您可以捕获 JSON 文件并显示“无效的用户名或密码!”页面。您在使用正确凭据时遇到相同错误的问题,对吗?检查 config/auth.php 文件具有正确的用户模型名称并且用户模型是 Authenticatable

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章