简体   繁体   English

laravel中间件在Ajax请求网址中不起作用

[英]laravel middleware is not working in ajax request url

I like to use ajax to insert into database and get back to show it. 我喜欢使用ajax插入数据库并返回显示它。 I have ajax like this 我有这样的ajax

$.ajax({
 method: 'POST',
 url: "{{ route('comments.store') }}",
 data: {
 comment: 1,
 comment_text: comment_text,
 post_id: post_id,
 "_token": "{{ csrf_token() }}"
});

and in Url route('comments.store) is protect by middleware('auth') in my controller 并在网址中,route('comments.store)由我的控制器中的中间件('auth')保护

public function __construct()
{
   $this->middleware('auth')->except(['index']);
}

public function store( Request $request ) {
   if(Auth::check()){
      if ( isset( $request->comment ) ) {
         $comment = new Comment( [
         'comment' => $request->comment_text,
         'user_id' => Auth::id(),
         'post_id' => $request->post_id
      ] );
      $comment->save();
      $comments = Comment::find( $comment->id );
     return response( $comments );
    }
}
return redirect()->route( 'home.post.show', $request->post_id );
}

when the user is logged it worked normal and response $comment row. 当用户登录时,它可以正常工作并响应$ comment行。

but when user is not logged the middleware not redirect user to logging page and it response error "unauthenticated". 但是,当用户未登录时,中间件不会将用户重定向到登录页面,并且它会响应错误“未经身份验证”。

how to resolve it need help. 如何解决它需要帮助。 Thanks You.. 谢谢..

Add an error callback function to your jQuery Ajax to redirect the user to the login page if Unauthorized 向您的jQuery Ajax添加error回调函数,以将用户重定向到登录页面(如果未经授权)

$.ajax({
    method: 'POST',
    url: "{{ route('comments.store') }}",
    data: {
        comment: 1,
        comment_text: comment_text,
        post_id: post_id,
        "_token": "{{ csrf_token() }}"
    },
    success: function (data) {

    },
    error : function (jqXHR, textStatus, errorThrown) {
        // User Not Logged In
        // 401 Unauthorized Response
        window.location.href = ' login page';
    }
});

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

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