TokenMismatch Error on Ajax Requests in Laravel

随声附和 提交于 2019-12-23 18:13:38

问题


I am getting TokenMismatch Error on Ajax Submit when I submit form it gives me error. Here I am using Laravel 5.2. Where I am passing X-CSRF-TOKEN on ajax call. Set Token on on meta on default.blade.php. I've tried all possible solutions from StackOverflow.

  1. Changing permission of storage folder.
  2. Tried clearing cache.
  3. Try adding Route::group(['middleware' => ['web','auth']], function () {
  4. Adding token to header of ajax function.
  5. Tried adding token field inside form.

Can anyone find any solution from below code.

Any idea where I'm going wrong? Any help will be appreciated

Below is my Category HTML Form category.blade.php:

<form method="POST" name="category-add-form" id="category-add-form" action="{{route("category-add")}}" accept-charset="UTF-8">
    {{csrf_field()}}
    <div class="form-group">
        <label for="title">Category Title:</label>
        <input class="form-control" name="category_title" type="text" value="" id="category_title">
    </div>
    <div class="form-group">
        <label for="body">Description:</label>
        <textarea class="form-control" name="category_description" cols="50" rows="10" id="category_description"></textarea>
    </div>
    <div class="form-group">
        <input class="btn btn-primary form-control" type="submit" value="Add CAtegory">
    </div>
</form>

Below id my app.js.

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

Below is my category-add.js here is my ajax code. I've not included whole function.

var request;
var $inputs = $("#category-add").find("input, select, button, textarea");
var formData = new FormData($("#category-add")[0]);
request = $.ajax({
    url: $("#category-add").attr("action"),
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    dataType: "json",
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

request.done(function (response, textStatus, jqXHR) {
    //Notification.init(response.message);
    //App.unblockUI('.block-panel-box');
});
request.error(function (response, textStatus, jqXHR) {
    //App.unblockUI('.block-panel-box');
});
request.always(function () {
    $inputs.prop("disabled", false);
});

Below is my default.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Test Project</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="width=device-width, initial-scale=1" name="viewport" />
        <meta name="csrf-token" content="{{csrf_token()}}">
        <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/font-awesome.min.css")}}" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/simple-line-icons.min.css")}}" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/bootstrap.min.css")}}" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/components-md.min.css")}}" rel="stylesheet" id="style_components" type="text/css" />
        <link href="{{asset("public/css/plugins-md.min.css")}}" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/layout.min.css")}}" rel="stylesheet" type="text/css" />
        <link href="{{asset("public/css/blue.min.css")}}" rel="stylesheet" type="text/css" id="style_color" />
        <link href="{{asset("public/css/responsive.css")}}" rel="stylesheet" type="text/css" />
        <link rel="shortcut icon" href="favicon.ico" />
    </head>
    <body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-sidebar-closed page-md">
        @include('user.layout.header')
        <div class="clearfix"> </div>
        <div class="page-container">
            @include('user.layout.sidebar')
            <div class="page-content-wrapper">
                @yield('content')
            </div>
        </div>
        @include('user.layout.footer')
        <div class="quick-nav-overlay"></div>
        <script src="{{asset("public/js/jquery.min.js")}}" type="text/javascript"></script>
        <script src="{{asset("public/js/bootstrap.min.js")}}" type="text/javascript"></script>
        <script src="{{asset("public/js/jquery.slimscroll.min.js")}}" type="text/javascript"></script>
        <script src="{{asset("public/js/app.min.js")}}" type="text/javascript"></script>
<script src="{{asset("public/js/category-add.js")}}" type="text/javascript"></script>
    </body>
</html>

Below is my category route file route.php

Route::group(['middleware' => ['web','auth']], function () {
    Route::post('/category-add', array("as" => "category-add","uses" => "CategoryController@store"));
});

Below is my CategoryController.php

class CategoryController extends Controller {
    public function store(Request $request) {
        $inputs = $request->all();
        $category = Category::create($inputs);
        if($category){
            $responseArray = array("status"=>true,"message"=>"Category successfully created");
        } else {
            $responseArray = array("status"=>false,"message"=>"Could not add category please try again later");
        }
        return response()->json($responseArray);
    }
}

Below is my .env file

APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:ratSluNv930gb3wp1UOabW6Ze3jEJn3ixtTX/wgqYZc=
APP_URL=http://project.dev/ts/cart-products

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cart-products
DB_USERNAME=hellocart
DB_PASSWORD=j@yshre33r@m

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

Below is my config/session.php file

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'cart-products',
    'path' => '/ts/cart-products', //Change path variable URL form '/cart-products' to '/ts/cart-products'
    'domain' => null,
    'secure' => false,
    'http_only' => true,
];

Below is my Kernal.php

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,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

回答1:


In your case, you haven't properly set the Session Cookie Path in config/session.php to sub subdirectory as you project is not in root of your domain.

So if your APP_URL is http://project.dev/ts/cart-products

then your path in config/session.php should be as follow

'path' => '/ts/cart-products'

you forgot to add '/ts'.




回答2:


I think you should inject '_token' in data will be sent. Like that

data : {
'_token' : "{{ csrf_token() }}",
'data'   : formData
}



回答3:


I would try to remove the "helpers" entry in category-add.js, then copy the "ajaxSetup" in the same file, bevor send the ajax request.




回答4:


<div class="quick-nav-overlay"></div>
        <script src="{{asset("public/js/jquery.min.js")}}" type="text/javascript"></script>
        <script src="{{asset("public/js/bootstrap.min.js")}}" type="text/javascript"></script>
        <script src="{{asset("public/js/jquery.slimscroll.min.js")}}" type="text/javascript"></script>
<script type="text/javascript">
    var _token = "{{ csrf_token() }}";
</script>
        <script src="{{asset("public/js/app.min.js")}}" type="text/javascript"></script>
<script src="{{asset("public/js/category-add.js")}}" type="text/javascript"></script>

As you can see I added var _token = "{{ csrf_token() }}"; before your js files, so you can reuse this variable in any js file that implement into this blade, and in ajax you just do like this:

request = $.ajax({
    url: $("#category-add").attr("action"),
    type: "POST",
    data: {
        '_token' : _token,
        'data'   : formData
    },
    processData: false,
    contentType: false,
    dataType: "json"
});



回答5:


Follow the step

project folder/app/http/kernal.php

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

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

put this line in comment

\App\Http\Middleware\VerifyCsrfToken::class,




回答6:


you can set X-CSRF-TOKEN like that. see for more detail laravel official site

<meta name="csrf-token" content="{{ csrf_token() }}">

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


来源:https://stackoverflow.com/questions/44669741/tokenmismatch-error-on-ajax-requests-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!