$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('/rsa_post')}}",
type: "post",
dataType: "json",
data: {key: 'value'},
success: function(data){
}
}, 'json');
排除csrf保护url
比如要访问的url为 http://www.landui.com/posts 现在想排除 posts 相关资源路由,则在App\\Http\\Middleware\\VerifyCsrfToken::class 中添加路由如下:
protected $except = [
'posts',
'posts/*'
];
注意方法二将无法对photo相关路由进行CSRF防护,所以请根据实际情况选择
关闭csrf保护
当我们不想启用框架自带的csrf防护的时候,进入:laravel/app/Middleware/VerifyCsrfToken.php 找到csrf的中间件,修改代码如下
public function handle($request, Closure $next){
// 使用CSRF
return parent::handle($request, $next);
// 禁用CSRF
//return $next($request);
}
有的时候我们既需要开启CSRF防护,又需要在一些特性的post请求时不带csrf_token(),laravel框架为我们提供了一个特殊的属性。
class VerifyCsrfToken extends BaseVerifier {
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [ // 'upload', 'rsa_post', ];
/* public function handle($request, Closure $next)
{
// 使用CSRF
return parent::handle($request, $next);
// 禁用CSRF
//return $next($request);
}*/
}
这段代码的意思是利用except来进行路由过滤。在我们except中的是我们不想被防护的路由名称。此处的upload和rsa_post,都是我需要post方式访问的路由。