DEV Community

Cover image for Oh No... CORS Error! A Backend Developer's Journey
Bashua Mutiat
Bashua Mutiat

Posted on

Oh No... CORS Error! A Backend Developer's Journey

As a frontend developer, encountering the "CORS error" message was a common but frustrating experience. While I didn't fully understand the cause, I knew it was a recurring challenge when dealing with APIs provided by backend developers. But when I decided to start my journey as backend developer, I realized that I was now in the same boat.

sad image

I remember creating my first API and then testing it in a react project, only to be met with the same CORS error. Initially, I was confused and uncertain about the cause.
Of course, I had to turned to Google my friend 😊 and read various articles about CORS (Cross-Origin Resource Sharing).

I learned that CORS is a security feature enforced by browsers to prevent web applications from making requests to a different domain than the one that served the web page. While essential for security, it is a significant challenge for development.After going through different articles, these were the steps I followed to resolve the issue

Step 1: Install the cors package

Since I hadn’t already installed the cors package, I did so by running the following command:

npm install cors
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure CORS to Allow Specific Origins

First, I configured my server to allow requests from specific origins by using the cors middleware.

const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {
  origin: ['http://localhost:3000', 'https://edture.vercel.app'],
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true,
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

app.get('/api/data', (req, res) => {
  res.json({ message: 'Data fetched' });
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Testing

To ensure the CORS configuration worked locally, I tested locally on the frontend port I had allowed.
I checked the network tab in the browser's developer tools to ensure the request was successful and no CORS errors appeared.
I also did the same on the live frontend url I specified.

I realized that there might be scenarios were i would want to test my api from any origin, so I had to allow all origins

const express = require('express');
const cors = require('cors');
const app = express();

// Using the CORS middleware with the default configuration to allow all origins
app.use(cors());

app.get('/api/data', (req, res) => {
  res.json({ message: 'Data fetched' });
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

By following these steps, I was able to configure my backend server to handle CORS properly, both for specific origins and for allowing all origins. This enabled my frontend application to make requests without encountering CORS errors.

In the next two months, I will be participating in the HNG internship, focusing on backend development. My aim is to enhance my skills as a backend developer. Reflecting on my experience as a finalist in the frontend development track during the last HNG internship, I realized how much those challenges contributed to my growth as a developer. The HNG internship provides an excellent opportunity to gain practical experience and further my knowledge, I look forward to becoming a better Backend Developer.

For anyone interested in learning more about the HNG internship, you can visit their website HNG Internship. The program is free, but for those seeking a certificate and job opportunities, there is a premium option available - HNG Premium.

Top comments (0)