I\'m trying to give users on my website \"points\" or \"credits\" for tweeting about out the brand name.
I have the fancy twitter widget on the appropriate view...>
If you're including Rails meta data in the HTML header with <%= csrf_meta_tags %> it'll generate the following.
You can pull the CRSF token from the meta data and pass it into your async request.
Using the native js fetch method you can pass it in as a x-csrf-token header.
This is a trimmed onSave handler for a React component that enhances a standard Rails form.
onSaveHandler = (event) => {
const data = "Foo Bar";
const metaCsrf = document.querySelector("meta[name='csrf-token']");
const csrfToken = metaCsrf.getAttribute('content');
fetch(`/posts/${this.props.post_id}`, {
method: "PUT",
body: JSON.stringify({
content: data
}),
headers: {
'x-csrf-token': csrfToken,
'content-type': 'application/json',
'accept': 'application/json'
},
}).then(res => {
console.log("Request complete! response:", res);
});
}
Forgery protection is a good idea. This way we stay secure and don't mess with our Rails configuration.
Using gem 'rails', '~> 5.0.5' & "react": "^16.8.6",