Fixing CORS Error: My experience as a backend developer

Hello there ๐Ÿ‘‹,

My name is Tabitha and I'm an aspiring Software Developer, I have basic skills in backend development and frontend development. I recently got accepted into the HNG11 internship and plan to use this wonderful opportunity to better sharpen my skills in web development and learn from industry experts and mentors. I will also use this opportunity in gaining the necessary experience in solving real world problems. You can learn more about the HNG internship at https://hng.tech/internship. If you want to to know more about their premium internship, you can also access this link at https://hng.tech/premium.

This blog post being the first task assigned for the HNG11 internship, I will be telling you about a difficult backend problem I had to solve and my approach to solving it.

In one of my recent capstone project from my last Bootcamp at Shecode Academy program(A Bootcamp for learning web development), I faced a challenge where my API response was being blocked due to CORS (cross-origin Resource sharing) errors. Being new to backend development, I didn't understand what this error meant at first or why the front-end team was getting an error from using my API seeing as my API worked perfectly well on testing using POSTMAN (an API development and testing tool ).

My group and I were working on a capstone project, an event management web application, and my role as the backend developer was to develop a RESTful API to enable organizers manage and edit events. The front-end team kept getting CORS error after sending requests to the API I developed. This slowed down our development as we tried to debug the given error. After going through my code to see what the cause was and some research about the error, I was able to diagnose and fix the error from my end.

Now this was my approach to solving the error;

Understanding what CORS was:

CORS (Cross-Origin Resource sharing) is a security feature in browsers that enforces the same-origin policy, which restricts web pages from making requests to a different origin or domain than the one that served the page. This meant that if my API server runs on https://example.com:3000, and a web-page sends request from a different origin or domain like https://example.com:5000, it would violate the same-origin policy and hence response from the server side would be blocked. Although this is a good security feature implemented by browsers to prevent malicious activities, but it will pose a challenge for my API because the domain on which the request was being sent from was different from that on which my API was served on.

Fixing the CORS error:

Now that I fully understood what the error was all about, the next step was how I could fix it. I fixed the error by adjusting my server configuration to allow cross-origin requests. I did this by adding the CORS middleware. I used the "cors" package for a straightforward setup. Using the "cors" package is the simplest way to enable CORS for my express server (I used Node.js with express.js as the development tool for my API) , it will handle setting the required headers.

Here is a step-by-step guide on how I used the package;

  1. I started by installing the package on my local machine. (You need to have node.js and npm installed in your machine before you can do this, You can find how to set up node.js here).
npm install cors
  1. Then I required and used the "cors" middleware in my express app. (You need to have express.js installed).

     npm install express
    

    For installing the express.js

here is the code to require and use the "cors" middleware in the express app

const cors = require('cors');
app.use(cors());

Here is the full server code in the index.js or app.js file using my code as an example;

const express = require('express');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
require('dotenv').config();

// route declaration
const eventsRouter = require('./routes/Events');
const authRouter = require('./routes/auth');

const app = express();

// Enable CORS for all route
app.use(cors());

//parse JSON and URL-encoded data
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//parse cookies
app.use(cookieParser());

app.use(eventsRouter);
app.use(authRouter);

module.exports = app;

This will allow request from any origin.

After making the necessary changes, the next thing I did was to ask the front-end team to refresh their browser and try sending the request again, and this time they got the needed response from my API. So there you have it, I was able to successfully solve the problem of cors error using this approach.

1
Subscribe to my newsletter

Read articles from Imafidon Tabitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Imafidon Tabitha
Imafidon Tabitha