简体   繁体   中英

TokenMismatchException in VerifyCsrfToken.php Laravel 5.2

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM