当构建由 JavaScript 驱动的应用时,可以方便地让 JavaScript HTTP 函数库发起每一个请求时自动附上 CSRF 令牌。默认情况下, resources/js/bootstrap.js 文件会用 Axios HTTP 函数库注册的 csrf-token meta 标签中的值。如果你不使用这个函数库,你需要手动为你的应用配置此行为。
从bootstrap.js中的以下代码片段可以看出,当使用 Axios HTTP函数库作为请求时,CSRF 令牌会自动传入 X-CSRF-TOKEN 请求头。 如果你不是用 Axios 作为 HTTP 请求库的话(比如用 jQuery),那么就需要你手动配置了。
1/** * Next we will register the CSRF Token as a common header with Axios so that * all outgoing HTTP requests automatically have it attached. This is just * a simple convenience so we don't have to attach every token manually. */let token = document.head.querySelector('meta[name="csrf-token"]'); 2 3if (token) { 4 window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; 5} else { 6 console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); 7}
其中 document.head.querySelector('meta[name="csrf-token"]'); 会读取 <meta name="csrf-token" >的值,所以应该在模板文件里面加上 <meta name="csrf-token" content="{{ csrf\_token() }}">标签。
值得注意的是:当不是用 Axios 作为 HTTP 请求库的话,比如用 jQuery 那么通过Axios自动附上 CSRF 令牌是无效的,需要我们手动设置headers参数将 CSRF 令牌传递给服务器,如:
1$.ajax({ 2 url: "{{ route('post') }}", //处理页 3 type:"POST", 4 headers: { 5 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 6 }, 7 dataType: "json", 8 data: { title: "标题内容", body: "主要内容"}, 9 success: function(result,status,xhr){ 10 alert("~成功~,返回结果:" + result.message + ",返回状态:"+status+",xhr:"+xhr.responseText + ",status: " + xhr.status + ",responseJSON: " + xhr.responseJSON); 11 }, 12 error: function(xhr,status,error){ 13 alert("~失败~, xhr: " + xhr.responseText + ",返回状态:" + status + ",错误:" + error + ",status: " + xhr.status + ",responseJSON: " + xhr.responseJSON); 14 } 15});