My frontend is a separate Brunch.io AngularJS app. Since my frontend runs on http://localhost:3333 and my Phoenix backend on http://localhost:4000 I get this error when trying to POST to http://localhost:4000/api/users/register
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore not allowed access. The response had HTTP status code 404.
So I think it is a CORS issue. How can I send the headers in phoenix?
This is my router.ex
scope "/api", MyApp do
pipe_through :api
# Users
post "/users/register", UserController, :register
end
This is my UserController
defmodule MyApp.UserController do
use MyApp.Web, :controller
def register(conn, params) do
IO.puts(inspect(params))
conn
|> put_status(201)
|> json %{ok: true, data: params}
end
end
An Elixir Plug to add Cross-Origin Resource Sharing (CORS). Add this plug to your mix.exs dependencies: When used together with the awesomeness that's the Phoenix Framework please note that putting the CORSPlug in a pipeline won't work as they are only invoked for matched routes.
2. How to Enable CORS Mechanism There are two ways by which we can enable CORS in JAX-RS. The first and the most basic way is to create a filter to inject necessary response header at run-time in every request. The other one is to manually add an appropriate header in each URL endpoint.
You can enable CORS functionality in HAProxy by using the HAProxy CORS Lua Library. It adds the following: When a request is received, it checks for the existence of an Origin header. An Origin header lets you know that the browser is expecting a CORS response or else it will block the request.
CORS is a mechanism for whitelisting domains that would otherwise have been restricted by the browser’s same-origin policy. Without enabling CORS, the request flow looks like this: JavaScript code running on a webpage makes an asynchronous request to an API URL. The server receives it and returns a valid response.
You have a few options that will wire up cors for you: https://hex.pm/packages?search=cors&sort=downloads
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With