游.程 2016-02-10 12:29 采纳率: 0%
浏览 57

Laravel 5.2 Ajax发布403

I'm having some issues with Laravel 5.2 when I do an ajax POST I get a 403 error

1) Ajax POST request

$.ajax({
            headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            },

            data: {category_id:category_id,  _token: $('meta[name="csrf-token"]').attr('content')},
            url: '/admin/gallery/create/ajax',
            method: 'POST',
            success: function(data)
            {
                console.log(data);
                $('#object').empty();
                $('#object').append(data);
            },
            error: function(msg)
            {
                console.log(msg);
            }
        });

2) Route

  Route::post('admin/gallery/create/ajax',           ['as' => 'gallery.ajax',    'uses' => 'GalleryController@getObject']);

3) Controller

public function getObject(Request $request){
        $data = array();
        if($request->category_id == 'users'){
            $allItems = User::all();
            foreach ($allItems as $key => $item) {
                $data += array($key=>'<option value="'.$item['name'].'">'.$item['name'].'</option>');
            }
        }
        if($request->category_id == 'authors'){
            $allItems = Author::all();
            foreach ($allItems as $key => $item) {
                $data += array($key=>'<option value="'.$item['name'].'">'.$item['name'].'</option>');
            }
        }
        if($request->category_id == 'galleries'){
            $allItems = Gallery::all();
            foreach ($allItems as $key => $item) {
                $data += array($key=>'<option value="'.$item['name'].'">'.$item['name'].'</option>');
            }
        }

        return $data;
    }

4) result

POST 403 (Forbidden)

5) but with route:

Route::post  ('admin/gallery/create/ajax', function(\Symfony\Component\HttpFoundation\Request $request){
    if (Session::token() == Request::header('x-csrf-token'))
    {
        echo $request->category_id;
    } else {
        return 'ERROR';
    }
});

6) result

request done

7) with GET all work fine

$.ajax({
    headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    },
    data: {category_id:category_id},
    url: '/admin/gallery/create/ajax/',
    method: 'get',
    success: function(data)
    {
        $('#object').empty();
        $('#object').append(data);
    },
    error: function(msg)
    {
        console.log(msg);// если ошибка, то можно посмотреть в консоле
    }
});

ROUTE GET

Route::get      ('/admin/gallery/create/ajax/',         ['as' => 'gallery.ajax',    'uses' => 'GalleryController@getObject']);
  1. GET RESULT

9. Need help with AJAX POST

  • 写回答

2条回答 默认 最新

  • larry*wei 2016-02-10 13:01
    关注

    Make sure you added your route to the web middleware group. Otherwise the token will not be verified.

    The web middleware group looks like this:

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
    

    As you can see it verifies the token in \App\Http\Middleware\VerifyCsrfToken::class,.

    So in your routes.php file, add the middleware group as the following:

    Route::group(['middleware' => ['web']], function () {
        // Your route goes here
    });
    
    评论

报告相同问题?