Installing CORS in Elixir-Phoenix Application

Search for a command to run...

Nice Brother Can You write a post about GO vs Elxir for Backend Applications
Motivation Recently, I tried to learn some low-level system programming stuff. I am a Mac user, and I thought that everything that works on Linux should also work on Mac. After all, Mac is a Unix-based system 😊. I guess we all heard this. Oh boy! I ...

Problem Statement While working on a Nestjs project, I encountered a weird problem related to the database column. I was trying to insert a record into a MySQL table using TypeORM. The error I was experiencing stated that a specific column “cannot be...

Recently, I was exploring design patterns courses on my LinkedIn Learning subscription. I came across a course, Node.js: Design Patterns by Alex Banks. It is a wonderful, easy-to-understand course. I started with the Builder Pattern, and the explanat...

Suppose you are working on a table in a LiveView project. This table has limited static data of not more than one page (you can avoid questions about pagination in the comment section 😊). From a user's point of view, it becomes hard to look into the...

Recently, while working on one of my personal Elixir projects. I came across a scenario where I needed to make some changes to the database schema.The changes mainly revolve around adding and removing indexes due to changes in the business requiremen...

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.
cors_plugmix phx.new --no-webpack --no-html my_blog_api. mix ecto.create to run the migration.mix.exs file and add dependency. {:cors_plug, "~> 2.0"},. Install dependency by running mix deps.get.
To configure cors we need to add it in our plug pipeline.
endpoint.ex file. In the file right below plug MyBlogApiWeb.Router add this line plug CORSPlug, origin:"*". The option origin means, what origin we should allow traffic from.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.👇