首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何允许在Elixir中使用plug_cowboy的CORS?

我如何允许在Elixir中使用plug_cowboy的CORS?
EN

Stack Overflow用户
提问于 2021-08-22 15:16:07
回答 1查看 137关注 0票数 1

我正在尝试通过在其他地方进行API调用来访问这些端点,我如何才能允许使用CORS呢?我在localhost:4001上运行它,并从localhost:3000 (react)进行API调用。提前谢谢。如果您需要任何额外的信息(或文件),请随时询问。

代码语言:javascript
复制
defmodule Api.Endpoint do
  @moduledoc """
  A plug that parses requests as JSON,
  dispatches responses and
  makes necessary changes elsewhere.
  """

  use Plug.Router

  plug Plug.Logger

  plug :match
  # Using Poison for JSON decoding
  plug(Plug.Parsers, parsers: [:json], json_decoder: Poison)
  plug :dispatch

  get "/ping" do
    send_resp(conn, 200, Poison.encode!(%{response: "pong!"}))
  end

  post "/events" do
    {status, body} =
      case conn.body_params do
        %{"events" => events} -> {200, process_events(events)}
        _ -> {422, missing_events()}
      end

    send_resp(conn, status, body)
  end

  defp process_events(events) when is_list(events) do
    Poison.encode!(%{response: "Received Events!"})
  end

  defp process_events(_) do
    Poison.encode!(%{response: "Please Send Some Events!"})
  end

  defp missing_events do
    Poison.encode!(%{error: "Expected Payload: { 'events': [...] }"})
  end

  match _ do
    send_resp(conn, 404, "oops... Nothing here :(")
  end
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-22 21:31:39

基于你的代码,就像@WeezHard所说的那样使用corsica

代码语言:javascript
复制
defmodule Api.CORS do
  use Corsica.Router,
  origins: ["http://localhost:3000"],
  allow_credentials: true,
  max_age: 600

  resource "/public/*", origins: "*"
  resource "/*"
end

然后在你的端点中

代码语言:javascript
复制
defmodule Api.Endpoint do
  @moduledoc """
  A plug that parses requests as JSON,
  dispatches responses and
  makes necessary changes elsewhere.
  """

  use Plug.Router

  plug Plug.Logger
  plug Api.CORS
  ...
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68882645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档