VerifyCsrfToken.php第67行中的TokenMismatchException - Laravel 5.2

时间:2016-06-28 15:13:28

标签: laravel laravel-5.2

我正在从一个教程开始研究这个项目但是我在VerifyCsrfToken.php第67行得到了这个TokenMismatchException当我尝试向视图添加新类别时出错我在互联网上尝试了一切: - 添加

<input type="hidden" name="_token" value="{{ Session::token() }}"> 

或添加

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

我的代码也删除了CSRF middileware无效

这是原始代码

视图

    @extends('layouts.admin-master')

@section('styles')
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="{{ URL::secure('src/css/categories.css') }}" type="text/css" />
@endsection

@section('content')
    <div class="container">
        <section id="category-admin">
            <form action="" method="post">
                <div class="category-input">
                    <label for="name">Category Name</label>
                    <input type="text" name="name" id="name">
                    <button type="submit" class="btn">Create Category</button>

                </div>


            </form>
        </section>
        <section class="list">
            @foreach($categories as $category)
                <article>
                    <div class="category-info" data-id="{{ $category->id }}">
                        <h3>{{ $category->name }}</h3>
                    </div>
                    <div class="edit">
                        <nav>
                            <ul>
                                <li class="category-edit"><input type="text"></li>
                                <li><a href="">Edit</a></li>
                                <li><a href="" class="danger">Delete</a></li>
                            </ul>
                        </nav>
                    </div>
                </article>
            @endforeach
        </section>
        @if($categories->lastPage() > 1)
            <section class="pagination">
                @if($categories->currentPage() !== 1)
                    <a href="{{ $categories->previousPageUrl() }}"><i class="fa fa-caret-left"></i> </a>
                @endif
                @if($categories->currentPage() !== $categories->lastPage())
                    <a href="{{ $categories->nextPageUrl() }}"><i class="fa fa-caret-right"></i> </a>
                @endif
            </section>
        @endif
    </div>

@endsection

@section('scripts')
    <script type="text/javascript">
        var token = "{{ Session::token() }}";
    </script>
    <script type="text/javascript" src="{{ URL::secure('src/js/categories.js') }}"></script>
@endsection

这是控制器

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Category;
use Illuminate\Support\Facades\Response;


class CategoryController extends Controller{

    public function getCategoryIndex()
    {
        $categories = Category::orderBy('created_at', 'desc')->paginate(5);
        return view('admin.blog.categories',['categories' => $categories]);
    }

    public function postCreateCategory(Request $request)
    {
        $this->validate($request, [
           'name' => 'required|unique:categories'
        ]);

        $category = new Category();
        $category->name = $request['name'];
        if($category->save()){
            return Response::json(['message' => 'Category Created Successfully!'], 200);
        }
        return Response::json(['message' => 'Error During Creation'], 404);
    }
}

那就是Js文件

var docReady = setInterval(function(){
    if (document.readyState !== "complete"){
        return;
    }
    clearInterval(docReady);

    document.getElementsByClassName('btn')[0].addEventListener('click',createNewCategory);
    var _token = document.getElementsByName('_token')[0].value;
//and append the value to form data
    formdata.append("_token", _token);
},100);



function createNewCategory(event) {
    event.preventDefault();
    var name = event.target.previousElementSibling.value;
    if(name.length === 0) {
        alert("Please A Valid Category Name!");
        return;
    }
    ajax("POST","/admin/blog/category/create", "name=" + name, newCategoryCreated, [name]);
}

function newCategoryCreated(params, success, responseObj){
    location.reload();
}

function ajax(method, url, params, callback, callbackParams){
    var http;

    if (window.XMLHttpRequest){
        http = new XMLHttpRequest();
    }else {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }

    http.onreadystatechange = function(){
        if (http.readyState == XMLHttpRequest.DONE){
            if (http.status == 200){
                var obj = JSON.parse(http.responseText);
                callback(callbackParams, true, obj);
            }else if(http.status ==400){
                alert("Category Could Not Be Saved. Please Try Again");
                callback(callbackParams, false);
            }else {
                var obj = JSON.parse(http.responseText);
                if (obj.message){
                    alert(obj.message);
                }else {
                    alert("Please Check The Name");
                }

            }
        }


    }

    http.open(method, baseUrl + url, true);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    http.send(params + "&_token=" + token);
}

那是路线

Route::post('/blog/category/create',[
            'uses' => 'CategoryController@postCreateCategory',
            'as' => 'admin.blog.category.create'
        ]);

Route::get('/blog/categories',[
            'uses' => 'CategoryController@getCategoryIndex',
            'as' => 'admin.blog.categories'
        ]);

请帮我解决这个错误我已经坚持了三天了

2 个答案:

答案 0 :(得分:0)

设置post_max_size = 100 mb或您需要的数量。

答案 1 :(得分:0)

在每个输入字段之前添加<input type="hidden" name="_token" value="{{ csrf_token() }}">,例如

 <input type="hidden" name="_token" value="{{ csrf_token() }}">  
<input type="text" name="last_name" id="last_name" placeholder="Last Name" class="form-control">