Installing CORS in Elixir-Phoenix Application

While developing API in any framework, we often come across error related to CORS. This post will help you fixing CORS issue in Elixir-Phoenix application.
Suppose, you have an Ember(or any Frontend SPA) application that runs on port 4200 and our Phoenix API is running on port 4000. When the Ember app tries to consume this API. It faces error related to cross-origin because it is not of the same domain.
cors_plug is a plugin available on hex.pm that helps us to deal with this problem. We will quickly create an application and configure cors_plug to see it in action.
Configuring cors_plug
- Create a phoenix app
mix phx.new --no-webpack --no-html my_blog_api. - Run
mix ecto.createto run the migration. - Now go to
mix.exsfile and add dependency.{:cors_plug, "~> 2.0"},. Install dependency by running
mix deps.get.To configure
corswe need to add it in our plug pipeline.- For that go to
endpoint.exfile. In the file right belowplug MyBlogApiWeb.Routeradd this lineplug CORSPlug, origin:"*". The optionoriginmeans, what origin we should allow traffic from. - Adding "*" means we are allowing traffic from everywhere. If we want to be specific for our ember application. We can add
origin: "localhost:4200".
Now you can add any endpoint in this phoenix application and test it out in the SPA of your choice. You won't be getting this error.
I hope you like this small post. If you any questions please add the comment below.👇




