VerifyCsrfToken.php Laravel 5.2中的TokenMismatchException [英] TokenMismatchException in VerifyCsrfToken.php Laravel 5.2

查看:78
本文介绍了VerifyCsrfToken.php Laravel 5.2中的TokenMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 5.2项目中遇到了可怕的VerifyCsrfToken错误.

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

相关代码如下:

引发错误的路由

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

当我尝试使用POST请求注册新用户时抛出错误

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

注册控制器

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'),
    ]);
}

预期产量

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

使我的问题与其他VerifyCsrf不匹配问题不同的原因是,我没有添加{{ csrf_token() }}隐藏字段的表单.我只是使用Postman(和curl)发送了请求,并且该用户需要注册.

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.

当我在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.

谢谢

推荐答案

将令牌存储在根刀片文件中.如果仅使用默认视图,则可能位于layout/main.blade.php

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() }}">

如果使用jQuery,您现在可以指示它在所有请求标头中包含令牌.

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')
       }
   });

如果仍然出现错误,请遵循: https://gist.github.com/ethanstenis/3cc78c1d097680ac7ef0

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

这篇关于VerifyCsrfToken.php Laravel 5.2中的TokenMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆