Here's how to get CORS working with Fetch API

Just spent 2 hours on this…

  1. Follow :cors_plug setup.
# mix.exs
defp deps, do: [
  {:cors_plug, "~> 2.0"},
  # ...

# endpoint.ex
  plug CORSPlug, origin: ["http://localhost:4000"]
  plug <YOUR APP>Web.Router
  1. In your webpage’s controller, add token: get_csrf_token() to your render/3
def index(conn, _params), do: render(conn, "index.html", token: get_csrf_token())
  1. In your JS:
fetch('http://localhost:4000/upload', {method: 'POST', mode: 'cors', headers: {'x-csrf-token': '<%= @token %>'}, body})

Key details:

  • DON’T use https
  • DON’T use '_csrf_token'

P.S. If you’re dealing with file uploads…

Not using https doesn’t seem very safe though? o.O

1 Like