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 有赏,i卡绘世画不出
    • ¥15 如何用stata画出文献中常见的安慰剂检验图
    • ¥15 c语言链表结构体数据插入
    • ¥40 使用MATLAB解答线性代数问题
    • ¥15 COCOS的问题COCOS的问题
    • ¥15 FPGA-SRIO初始化失败
    • ¥15 MapReduce实现倒排索引失败
    • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
    • ¥15 找一位技术过硬的游戏pj程序员
    • ¥15 matlab生成电测深三层曲线模型代码