Laravel

时间:2017-06-21 07:40:07

标签: php laravel laravel-5.2

我收到TokenMismatch Ajax错误提交时,我提交表单时给出了错误。我在这里使用Laravel 5.2。我在ajax电话上传递X-CSRF-TOKEN的地方。在default.blade.php上的元设置上设置令牌。我已经尝试了StackOverflow的所有可能解决方案。

  1. 更改存储文件夹的权限。
  2. 尝试清除缓存。
  3. 尝试添加Route::group(['middleware' => ['web','auth']], function () {
  4. token添加到a​​jax函数的标头中。
  5. 尝试在表单中添加token字段。
  6. 任何人都可以从下面的代码中找到任何解决方案。

    知道我哪里出错了吗?任何帮助将不胜感激

    以下是我的分类HTML表单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>
    

    下面是我的app.js

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

    下面是我的category-add.js这是我的ajax代码。我没有包括整个功能。

    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);
    });
    

    以下是我的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>
    

    以下是我的类别路线文件route.php

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

    以下是我的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);
        }
    }
    

    以下是我的.env文件

    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
    

    以下是我的config/session.php文件

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

    以下是我的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',
        ],
    ];
    

6 个答案:

答案 0 :(得分:2)

在您的情况下,您还没有正确地将config / session.php中的会话Cookie路径设置为子子目录,因为您的项目不在您的域的根目录中。

因此,如果您的APP_URL为 http://project.dev/ts/cart-products

那么你在config / session.php中的路径应该如下

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

您忘记添加&#39; / ts&#39;。

答案 1 :(得分:0)

我认为你应该在数据中注入“_token”。像那样

codec => multiline {
      pattern => "^[0-9]"
      negate => "true"
      what => "previous"
    }

答案 2 :(得分:0)

我会尝试删除category-add.js中的“helpers”条目,然后在同一个文件中复制“ajaxSetup”,bevor发送ajax请求。

答案 3 :(得分:0)

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

如你所见,我添加了var _token =&#34; {{csrf_token()}}&#34 ;;在你的js文件之前,所以你可以在任何实现到这个刀片的js文件中重用这个变量,在ajax中你只需要这样做:

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

答案 4 :(得分:0)

按照步骤

项目文件夹/ 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',
    ],
];

将这一行放在评论中

  

\应用\ HTTP \中间件\ VerifyCsrfToken ::类,

答案 5 :(得分:0)

您可以像这样设置X-CSRF-TOKEN。有关详细信息,请参阅laravel官方网站

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

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