Created
August 19, 2022 14:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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