douyun7285 2016-10-06 06:35
浏览 48
已采纳

VerifyCsrfToken.php Laravel 5.2中的TokenMismatchException

I have got the dreaded VerifyCsrfToken error in my Laravel 5.2 project.

Relevant codes are below:

Route which is throwing the error

Route::group(['middleware' => ['web']], function(){
    Route::resource('register', 'RegisterController');
});

Error is thrown when I try to register a new user using POST request

Register Controller

public function store(Request $request)
{
    return AppUser::create([
        'name' => $request->input('name'),
        'email' => $request->input('name'),
        'contact_number' => $request->input('contact_number'),
        'api_token' => str_random(60),
        'password' => $request->input('password'),
    ]);
}

Expected Output

{
  "email": "test.name",
  "contact_number": "654987123",
  "updated_at": "2016-10-06 06:30:26",
  "created_at": "2016-10-06 06:30:26",
  "id": 4
}

What makes my question different from the other VerifyCsrf mismatch questions are, I don't have a form to add a {{ csrf_token() }} hidden field. I just sent the request using Postman (and curl) and the user needs to be registered.

When I do the following edit on app/Http/Middleware/VerifyCsrfToken.php

protected $except = [
    '/*'
    //
];

The error disappears and it works as it should, but I don't think is the recommended way.

Thanks

  • 写回答

1条回答 默认 最新

  • du656637962 2016-10-06 07:31
    关注

    Store the token in the root blade file. if you are using only default view, then may be in layout/main.blade.php

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

    If using jQuery, you can now instruct it to include the token in all request headers.

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

    If you still get errors follow: https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题