使用Laravel提交POST请求出现The page has expired due to inactivity错误

来源:csdn博客 分类: 文章浏览史 发布时间:2020-08-31 15:40:44 最后更新:2020-08-31 浏览:949
转载声明:
本文为摘录自“csdn博客”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-08-31 15:40:44

使用Laravel提交POST请求出现The page has expired due to inactivity. Please refresh and try again.

问题:

提交POST请求,出现如下错误:

The page has expired due to inactivity. 

Please refresh and try again

这是由于在Laravel框架中有此要求:

任何指向 web 中 POST, PUT 或 DELETE 路由的 HTML 表单请求都应该包含一个 CSRF 令牌(CSRF token),否则,这个请求将会被拒绝。

解决办法1: 加上 CSRF token

<form method="POST" action="/profile">
{{ csrf_field() }}
    ...
</form>

也可以最新写法

<form method="POST" action="/profile">
    @csrf
    ...
</form>

如果是AJAX提交:

在页面头部加上csrf-token:

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

提交headers中增加 X-CSRF-TOKEN:

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

解决办法2: 移除 CSRF token

也可以在指定页面移除CSRF保护:

/app/Http/Middleware/VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

参考链接:

http://blog.csdn.net/qq_37107603/article/details/78891628
https://laravel.com/docs/5.6/csrf#csrf-introduction

[END]

php技术微信