phoneix 的跨域问题处理

 

比如  某个请求是http:// localhost:4000提供的,但是我们的前端应用程序将在http:// localhost:3000上运行 。

这样,就涉及到CORS跨域问题了,

 

为处理这个跨域错误,我们需要安装第三方库 {:cors_plug, "~> 1.1"},然后在sling/api/sling/endpoint.ex中添加配置。

#above content
 
    plug CORSPlug

 

添加CORS支持很容易。 我们只需要将cors_plug添加到我们的mix.exs文件中:

 {:cors_plug, "~> 1.3"}

例如:
defp deps do
  [
   ...
   {:cors_plug, "~> 1.3"}
  ]
end

 

现在,我们使用Control-C停止Phoenix服务器,并使用以下命令获取依赖项:

mix deps.get

我们需要将以下行添加到我们的lib /test / endpoint.ex文件中:

plug CORSPlug

最后重启Phoenix Server即可,这样就解决了跨域问题。

 

方法2:

defp set_resp_cors(conn, _params) do
    conn
      |> put_resp_header("Access-Control-Allow-Origin", "*")
      |> put_resp_header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
      |> put_resp_header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
      )
      |> put_resp_header("Access-Control-Allow-Credentials", "true")
  end

  即封装个函数,把header头的 几项配置 以*的方式 添加进去。

 

参考连接:Create login and signup pages · bnhansn/sling@50463f9 (github.com) 

Let’ s Build |> 使用 Elixir,Phoenix 和 React 打造克隆版的 Slack (part 3 )_安科网 (ancii.com)

 

posted @ 2022-06-15 17:40  孤独信徒  阅读(33)  评论(0编辑  收藏  举报