<meta name="csrf-token" content="{{ csrf_token() }}" />
Alpine.js CSRF Token
The fetch method now should have the X-CSRF-TOKEN specified inside the headers and then get the content of the "csrf-token" meta tag. For this example imagine we are going to send a "post" data to the backend to save a new post, the content should contain the "title", "slug" and "body" like below.
<form x-data="{ post: { title: '', slug: '', body: '', }, submit() { fetch('/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.head.querySelector('meta[name=csrf-token]').content }, body: JSON.stringify(this.post) }) .then((data) => console.log(data)) }">
/** * 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';
Leave a reply