在使用 AJAX 发送请求时,需要手动设置 CSRF 令牌。
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/your-ajax-url',
type: 'POST',
data: { example_data: 'example_value' },
success: function(response) {
console.log(response);
}
});
- 首先,通过
$.ajaxSetup
全局设置 AJAX 请求的头部,将 CSRF 令牌添加到 X-CSRF-TOKEN
头部中。
- 这个令牌可以从 HTML 页面的
<meta>
标签中获取,在 Laravel 的 Blade 模板中,可以使用以下代码添加 <meta>
标签:
<meta name="csrf-token" content="{{ csrf_token() }}">
- 然后,在发送 AJAX 请求时,服务器会验证
X-CSRF-TOKEN
头部中的令牌。
import axios from 'axios';
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').content;
axios.post('/your-ajax-url', {
example_data: 'example_value'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
- 使用
axios.defaults.headers.common
全局设置 Axios 请求的头部,将 CSRF 令牌添加到 X-CSRF-TOKEN
头部中。
- 同样,令牌从
<meta>
标签中获取。
在某些情况下,可能需要排除某些路由的 CSRF 验证,例如 API 路由。
在 app/Http/Middleware/VerifyCsrfToken.php
文件中,可以通过 $except
属性指定不需要 CSRF 验证的路由。
<?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<int, string>
*/
protected $except = [
'api/*',
];
}
- 在
$except
数组中添加需要排除 CSRF 验证的路由模式,这里的 api/*
表示所有以 api/
开头的路由都不需要进行 CSRF 验证。
在某些特殊情况下,可能需要手动验证 CSRF 令牌。
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
public function customVerify(Request $request)
{
$validator = Validator::make($request->all(), [
'_token' => 'required|string|in:' . csrf_token(),
]);
if ($validator->fails()) {
// 验证失败
return response()->json(['error' => 'CSRF token validation failed'], 403);
}
// 验证成功,继续处理请求
return response()->json(['message' => 'CSRF token verified successfully']);
}
- 使用 Laravel 的验证器手动验证
_token
字段是否等于当前的 CSRF 令牌。
- 如果验证失败,返回 403 错误;如果验证成功,继续处理请求。