菜鸟学习Laravel框架之提交POST请求出现The page has expired due to inactivity错误

使用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
  • 1
  • 2
  • 3

这是由于在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>
  • 1
  • 2
  • 3
  • 4

如果是AJAX提交:

在页面头部加上csrf-token:

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

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

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

解决办法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/*',
    ];
}
public function handle($request,\Closure $next){
        // 启用CSRF
        // return parent::handle($request, $next);
        //禁用CSRF
        return $next($request);
    }

解决方法3:不加载验证CSRF token

找到app/Http/Kernel.php文件,找到\App\Http\Middleware\VerifyCsrfToken::class,并注释掉即可(不推荐)

猜你喜欢

转载自blog.csdn.net/robin_sky/article/details/80802241
今日推荐