weixin_33709219 2018-07-06 16:59 采纳率: 0%
浏览 12

Laravel 419使用Ajax时出错

Okay let me explain first. I am sending a PUT request using ajax like this:

//ajax function
$(document).on("click", ".question_no", function(){
  current_color = rgb2hex($(this).css('background-color'));
  q_index = $(this).attr('id').slice(5);
  id_team_packet = $("#id_team_packet").val();
  // startTimer();
  if (current_color != '#ffc966') {
    $(this).css('background-color', "#ffc966");

    var status = "orange";

    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });

    $.ajax({
      url: '{{route('peserta.submit.ans.stat')}}',
      method: 'put',
      data: {q_index, id_team_packet},
      success: function(data){
        console.log(data)
      }
    })
  }
})

NOTE I already have my CSRF token setup in my head, which I also include in my ajax setup as you can see below. It works great :). But once I protect that route with a Middleware, like this:

 //middleware
 public function handle($request, Closure $next)
    {
      if (Auth::user()) {
        if (Auth::user()->role == 3) {
          return $next($request);
        }
         if ($request->ajax()) {
           return response()->json(['intended_url'=>'/'], 401);
         }
        return redirect('/');
      }
       if ($request->ajax()) {
         return response()->json(['intended_url'=>'/'], 401);
       }
      return redirect('/');
    }

//web.php
Route::middleware(['participant_only'])->group(function(){
  Route::put('/peserta/submit-answer-status', 'PesertaController@submitAnsStat')->name('peserta.submit.ans.stat');

});

As you can see it only accepts logged in user with a role of '3'. If user tries to log in, it redirects to '/'. Now I also check if the request is using ajax, which I return a message with code 401. But unfortunately, when the middleware is applied and I ajax it, it returns this error:

message 
exception   Symfony\Component\HttpKernel\Exception\HttpException
file    -\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php
line    203

But if once I remove the middleware it works. I don't know where the problem is. Oh on another note, If I exclude that particular route from verifycsrftoken it returns the right response both with the middleware and without.

My question is, where is the problem and how do I fix it? Thank you :)

  • 写回答

0条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 GEO下载数据的处理报错 :函数‘Meta’标签‘"data.frame"’找不到继承方法,如何解决?
      • ¥15 DLNM模型是否可以用二分类变量作为y变量
      • ¥15 android object box 一个实体多个表怎么写
      • ¥15 temux 启用docker 服务失败
      • ¥15 Flask 使用celery发送邮件出现‘目标计算机积极拒绝‘
      • ¥60 老人用的sd卡在手机里面不知道操作了什么,导致图片和视频变成了文件,取下sd卡连接电脑就是图中的样子,后缀改为.jpg才可以,需要用系统的画图软件才能打开,文件属性还是文件,有没有批量操作的解决办法
      • ¥15 超时跳出方法代码的返回值问题
      • ¥15 汇编语言程序设计设计,ascii码求数,再求数的BCD码
      • ¥30 Mask rcnn训练自己的数据集出现问题!
      • ¥20 研究人工智能时的几个问题