如何在API请求头n Laravel和vue3中设置X-XSRF-TOKEN或X-CSRF-TOKEN



如何在bootstrap.js.上设置Laravel 8中的XSRF-TOKEN

根据文件,它是自动处理的,但当我试图访问用户数据时,它会未经授权返回。

我的bosstrap.js代码

window._ = require('lodash');
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

如果您使用AJAX,您可以在任何请求之前执行此操作:

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

假设你的刀片视图中有一个元标签:

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

如果您无法从元标签中获取CSRF令牌,那么您可以通过vu/为所有正在使用的路由添加vu前缀,并通过将URI添加到VerifyCsrfToken中间件app/Http/Middleware/VerifyCsrfToken.php$except属性来从CSRF中排除URI。

<?php
namespace AppHttpMiddleware;
use IlluminateFoundationHttpMiddlewareVerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'vu/*',
];
}

文档

最新更新