duanhe1965 2014-12-14 20:49
浏览 50
已采纳

带路由的Laravel错误的Ajax

I have routing issue with laravel when calling ajax but I don't really understand what could be causing it since what I have should call ajax and return successfully. Any help would be greatly appreciated. Thank you!

Here is my ajax code

$.ajax({
            type: "POST",
            url: baseLocalUrl, //baseLocalUrl= "http://localhost:4567/admin/menuBuilder/1/save"
            data: 
            {
                html: $("#comment_area").text()
            },
            success: function(data){
                alert("success!");
            }


});

Here is my route

Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
.....
Route::post('menuBuilder/{role}/save' , array('uses' => 'AdminMenuBuilderController@saveHTML' ));
.....
});

Here is my controller method

public function saveHTML($roleId){
        //$decodeJson = Input::get('html');
        return "success";

}

This is the error I am getting

 POST http://localhost:4567/admin/menuBuilder/1/save 500 (Internal Server Error)

Laravel Log

production.ERROR: 500 - Exception @ /admin/menuBuilder/1/save
exception 'Illuminate\Session\TokenMismatchException' in /vagrant/app/filters.php:98

filters.php

<?php

/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/

App::before(function($request)
{
    //
});


App::after(function($request, $response)
{
    //
});

/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/

Route::filter('auth', function()
{
    if ( Auth::guest() ) // If the user is not logged in
    {
            return Redirect::guest('user/login');
    }
});

Route::filter('auth.basic', function()
{
    return Auth::basic();
});

/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/

Route::filter('guest', function()
{
    if (Auth::check()) return Redirect::to('user/login/');
});

/*
|--------------------------------------------------------------------------
| Role Permissions
|--------------------------------------------------------------------------
|
| Access filters based on roles.
|
*/

// Check for role on all admin routes
Entrust::routeNeedsRole( 'admin*', array('admin'), Redirect::to('/') );

// Check for permissions on admin actions
Entrust::routeNeedsPermission( 'admin/blogs*', 'manage_blogs', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/comments*', 'manage_comments', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/users*', 'manage_users', Redirect::to('/admin') );
Entrust::routeNeedsPermission( 'admin/roles*', 'manage_roles', Redirect::to('/admin') );

    /*
    |--------------------------------------------------------------------------
    | CSRF Protection Filter
    |--------------------------------------------------------------------------
    |
    | The CSRF filter is responsible for protecting your application against
    | cross-site request forgery attacks. If this special token in a user
    | session does not match the one given in this request, we'll bail.
    |
    */

    Route::filter('csrf', function()
    {
        if (Session::getToken() != Input::get('csrf_token') &&  Session::getToken() != Input::get('_token'))
        {
            throw new Illuminate\Session\TokenMismatchException;
        }
    });

    /*
    |--------------------------------------------------------------------------
    | Language
    |--------------------------------------------------------------------------
    |
    | Detect the browser language.
    |
    */

    Route::filter('detectLang',  function($route, $request, $lang = 'auto')
    {

        if($lang != "auto" && in_array($lang , Config::get('app.available_language')))
        {
            Config::set('app.locale', $lang);
        }else{
            $browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
            $browser_lang = substr($browser_lang, 0,2);
            $userLang = (in_array($browser_lang, Config::get('app.available_language'))) ? $browser_lang : Config::get('app.locale');
            Config::set('app.locale', $userLang);
            App::setLocale($userLang);
        }
    });
  • 写回答

1条回答 默认 最新

  • douyuliu9527 2014-12-14 21:20
    关注

    You need to include your CSRF token in the header of your AJAX call. Try this:

    In your HTML <head> block:

    <!-- This is one of the more common ways of accessing your CSRF token. -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    

    And for your AJAX call:

    var token = $('meta[name="csrf-token"]').attr('content');
    
    $.ajax({
      type: "POST",
      url: baseLocalUrl,
      data: {
        html: $("#comment_area").text()
      },
    
      // Added the CSRF token to the request header.
      header: {"X-CSRF-Token": token},
    
      success: function(data) {
        alert("Success!");
      }
    });
    

    And finally, in app/filters.php, change your CSRF filter to:

    Route::filter('csrf', function()
    {
      $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
      if (Session::token() != $token)
      {
        throw new Illuminate\Session\TokenMismatchException;
      }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题