Quick Tip
Use javascript fetch to post to a Phoenix controller
javascriptcsrf
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'}})
})
Tag Cloud
Phoenix Bolerplate
Generate a Phoenix Boilerplate and save hours on your next project.
6288
downloads
Try now
OR
SAAS Starter Kit
Get started and save time and resources by using the SAAS Starter Kit built with Phoenix and LiveView.
Subscribe for $39/mo to geat ahead!
Learn More