我知道这个问题被问到已经有一段时间了,但对于任何在那里搜索的人来说,不。你不必/sanctum/csrf-cookie
每次请求都打电话。在发出post | put | delete...
请求之前,您可以检查是否XSRF-TOKEN
设置了 cookie。如果不是,请调用/sanctum/csrf-cookie
路由(或任何您配置的路由)。请求完成后(XSRF-TOKEN
cookie 将由您的浏览器自动设置)您现在可以继续执行初始请求。
执行此操作的最佳位置是在拦截器中(如果您的 http 库支持它)。我将假设您正在使用 axios。
// Install with 'npm i js-cookie'. A library that helps you manage cookies
// (or just build your own).
import Cookies from 'js-cookie';
// Create axios instance with base url and credentials support
export const axiosInstance = axios.create({
baseURL: '/api',
withCredentials: true,
});
// Request interceptor. Runs before your request reaches the server
const onRequest = (config) => {
// If http method is `post | put | delete` and XSRF-TOKEN cookie is
// not present, call '/sanctum/csrf-cookie' to set CSRF token, then
// proceed with the initial response
if ((
config.method == 'post' ||
config.method == 'put' ||
config.method == 'delete',
/* other methods you want to add here */
) &&
!Cookies.get('XSRF-TOKEN')) {
return setCSRFToken()
.then(response => config);
}
return config;
}
// A function that calls '/api/csrf-cookie' to set the CSRF cookies. The
// default is 'sanctum/csrf-cookie' but you can configure it to be anything.
const setCSRFToken = () => {
return axiosInstance.get('/csrf-cookie'); // resolves to '/api/csrf-cookie'.
}
// attach your interceptor
axiosInstance.interceptors.request.use(onRequest, null);
export default axiosInstance;
XSRF-TOKEN cookie 带有到期时间。在那之后,浏览器将其删除。因此,只要您能找到 cookie,就可以安全地发出请求,而无需调用/sanctum/csrf-cookie
或任何您配置的请求。