TokenMismatchException in VerifyCsrfToken.php Laravel 5.2

一个人想着一个人 提交于 2019-12-12 02:25:24

问题


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:


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



来源:https://stackoverflow.com/questions/39889081/tokenmismatchexception-in-verifycsrftoken-php-laravel-5-2

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