简体   繁体   English

ajax调用laravel 5.2时出现401未经授权的错误

[英]401 Unauthorized error on ajax call laravel 5.2

when i am doing ajax call i am getting error as 401 Unauthorized.当我在做 ajax 调用时,我收到 401 Unauthorized 错误。

this is my ajax code:这是我的ajax代码:

var email=document.getElementById( "email" ).value;
  if(email)
  {
      var data = 'email='+ email;
      $.ajax({
              type: 'POST',
              dataType: "json",
              data: {"_token": "{{ csrf_token() }}","data":data},
              url: "{{ URL::to('admin/check_email_exit') }}",
              success: function (response) {
              if(response=="1")
              {
                  $( '#email_status' ).html('Email Already Exists');
                  return false;
              }
              else
              {
                  $( '#email_status' ).html("");
                  return false;
              }
       }
       });
  }
    else
    {
         $( '#email_status' ).html("");
         return false;
    }

my route:我的路线:

Route::post('admin/check_email_exit', 'CompanyController@check_email_exit');

this is my controller code that checks email exits or not:这是我的控制器代码,用于检查电子邮件是否退出:

public function check_email_exit(){
        $email = $_POST["email"];
        $user_email = DB::table('users')->where('email',$email)->select('*')->get();
        $use_email=count($user_email);
        if($use_email > 0 )
        {
            return "1";
        }
        else
        {
            return "0";
        }
    }

how to resolve this error..??如何解决这个错误..??

Just set X-CSRF-Token in ajax Request header只需在 ajax 请求头中设置X-CSRF-Token

headers: {
  'X-CSRF-Token': {{ csrf_token() }}
}

This may help you.这可能对你有帮助。

Check if you need the route that you are calling, the user must be authorized or not.检查您是否需要您正在调用的路由,用户是否必须被授权。 If the case is not, than you can try to define the route outside of auth middleware.如果不是这种情况,那么您可以尝试在auth中间件之外定义路由。 Something like this.像这样的东西。

Before:之前:

Route::group(['middleware' => 'auth'], function() {
    Route::get('route_name', [Controller::class, 'methd']);
    ... other routes
});

After:之后:

Route::get('route_name', [Controller::class, 'methd']);

Route::group(['middleware' => 'auth'], function() {
    ... other routes
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM