简体   繁体   English

VerifyCsrfToken.php Laravel 5.2中的TokenMismatchException

[英]TokenMismatchException in VerifyCsrfToken.php Laravel 5.2

I have got the dreaded VerifyCsrfToken error in my Laravel 5.2 project. 我在Laravel 5.2项目中遇到了可怕的VerifyCsrfToken错误。

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 当我尝试使用POST请求注册新用户时抛出错误

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. 使我的问题与其他VerifyCsrf不匹配问题不同的原因是,我没有添加{{ csrf_token() }}隐藏字段的表单。 I just sent the request using Postman (and curl) and the user needs to be registered. 我只是使用Postman(和curl)发送了请求,并且需要注册用户。

When I do the following edit on app/Http/Middleware/VerifyCsrfToken.php 当我在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 如果仅使用默认视图,则可能位于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. 如果使用jQuery,您现在可以指示它在所有请求标头中包含令牌。

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

If you still get errors follow: https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0 如果仍然出现错误,请遵循: https : //gist.github.com/ethanstenis/3cc78c1d097680ac7ef0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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