Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Created August 19, 2022 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shelob9/5c78c63946c98facfca11198aeb8d96f to your computer and use it in GitHub Desktop.
Save Shelob9/5c78c63946c98facfca11198aeb8d96f to your computer and use it in GitHub Desktop.
Using fetch to PUT data to a Laravel API that uses Laravel Sanctum. Sending the `X-XSRF-TOKEN` token to avoid error "CSRF token mismatch" with Laravel Sanctum
//https://stackoverflow.com/a/56071867/1469799
export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});
export const getCookie(name, defaultValue = null) => {
let cookies = getAllCookies();
return cookies.hasOwnProperty(name) ? cookies[name] : defaultValue;
}
fetch('/api/v1/rocks, {
method: "PUT",
body: JSON.stringify({
color: "red"
shiny: true
}),
credentials: 'include',
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": token,
"Accept": "application/json"
},
})
.then( r => r.json() )
.then( r => {
console.log(r);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment