Quick Tip
Use javascript fetch to post to a Phoenix controller
csrf
javascript
As in the case with Rails, Phoenix also has protection against cross site request forgery (crfs). If you want to post to a controller from a javascript file you need to add the token as a header manually. However, in phoenix the csrf token is provided when you render a form. So, unless there is already a form on the page, there is no token to read. To get around this, add this in the page header:
<%= csrf_meta_tag() %>
And then the post can be triggered with:
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
fetch('/posts', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token
},
body: JSON.stringify({post: {title: 'Awesome blogpost title'}})
})