Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling Cross-Origin Resource Sharing CORS in Phoenix / Elixir

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
like image 742
Ole Spaarmann Avatar asked Nov 05 '15 22:11

Ole Spaarmann


People also ask

How do I add Cross-Origin Resource Sharing (CORS) in Elixir?

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.

How do I enable Cors in JAX-RS?

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.

How do I enable Cors functionality in HAProxy?

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.

What is cors and how does it work?

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.


1 Answers

You have a few options that will wire up cors for you: https://hex.pm/packages?search=cors&sort=downloads

like image 155
Chris McCord Avatar answered Oct 10 '22 10:10

Chris McCord