<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> </head>
<meta name="csrf-token" content="{{ csrf_token() }}">
jQuery CSRF_TOKEN setup
If you are using jQuery to perform your Ajax then you can specify your code as follows.
$.ajax({ url : "YOUR_API_URL_HERE", method:"post", data : { "_token": @json(csrf_token()), }, ... });
Axios CSRF_TOKEN setup
By default Laravel ships Axios HTTP support so you have CSRF_TOKEN support already out of the box. If you are curious below is the code.
window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
AlpineJS, Native JS Fetch and etc
For AlpineJS and any regular JS applications, you can also make use of "fetch()" API. Do refer to the code below for the full code example.
fetch('YOUR_API_URL_HERE', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': @json(csrf_token()), }, body: JSON.stringify(this.formData) }) .then(() => { console.log('it works! yay') }) .catch(() => { console.log('there\'s something error here') })
Leave a reply