在 Phoenix / Elixir 中启用 Cross-Origin 资源共享 CORS

Enabling Cross-Origin Resource Sharing CORS in Phoenix / Elixir

我的前端是一个单独的 Brunch.io AngularJS 应用程序。由于我的前端在 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.

所以我认为这是一个 CORS 问题。如何在 phoenix 中发送 headers?

这是我的router.ex

  scope "/api", MyApp do
    pipe_through :api
    # Users
    post "/users/register", UserController, :register
  end

这是我的用户控制器

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

您有几个选项可以为您连接 cors: https://hex.pm/packages?search=cors&sort=downloads