How to Bypass the CORS Error in Browser?

How to Bypass the CORS Error in Browser?

CORS errors are common when making HTTP requests from one origin to another. Bypass the CORS errors easily with this methods easily

When I started to learn code and tried to create my first project Klingon Translator, I encountered the CORS error problem first.

I tried to use the fetch(URL) method to parse the API, but it gave an error:

Access-Control-error.png

I was stuck there for almost 2 weeks, and the figured out a way to solve it.

Now I realize that it’s not only me. Many of you who are learning to code is also going through the same problem.

So, I’ve decided to help you solve the problem once and for all!💪

Understanding the CORS Error

CORS stands for Cross-Origin Resource Sharing (CORS). It’s basically the browser’s security model, which prevents sharing data between different HTTP origins.

We only see a simplified version of our website, like arnabghosh.me, but actually, it means

  • Protocol: https://
  • Host: arnabghosh.me
  • Port: 443 (this is the port number typically used in HTTPS)

When I try to request information from a different origin, to my own domain origin, let's say from arnabghosh.me to mailboxvalidator.com, the browser automatically ads some CORS headers to the request:

  • Origin: https://arnabghosh.me
  • Access-Control-Request-Method:GET
  • Access-Control-Request-Headers: content-type

Similarly, when the mailboxvalidator.com server returns a response, it also attaches some CORS header to the response:

It looks something like this:

  • access-control-allow-credentials: true
  • access-control-allow-headers: content-type,x-tawk-token
  • access-control-allow-methods: POST,OPTIONS
  • access-control-allow-origin: https://mailboxvalidator.com

As you can see clearly, the server doesn’t allow origin arnabghosh.me. It only allows mailboxvalidator.com.

And that’s why the client-side app can’t use the data provided by a cross-origin server and shows the error.

Fixing the CORS Error

Solution 1: Allow CORS in the Backend

If you’re working in Express.js backend server, then it's super easy to solve.

All you need to do is use a cors middleware that’ll set the access-control-allow-origin header to your client-side domain.

For example, In this case, I’d do:

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

const cors = require('cors');

app.use(cors({
  origin: 'https://arnabghosh.me',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
}));

app.get('/', (req, res) => {
  res.send('All my data”')
})

Now if you again request data from your server, it shouldn't give any CORS error. And if you see the server response, it will show something like this:

  • access-control-allow-credentials: true
  • access-control-allow-headers: content-type,x-tawk-token
  • access-control-allow-methods: POST,OPTIONS
  • access-control-allow-origin: https://arnabghosh.me

Resolving the Error with Node.JS Proxy Server

The magic with this CORS error is that it only applies to server-browser communication and does not apply to server-server communication.

That means you can create a proxy server and get the third-party server working on your domain.

That's exactly what I did.

Here's the Node.js Code for you that created a proxy server around:api.mailboxvalidator.com/v1/validation/single

var express = require("express");
var request = require('request');

var app = express();

var port = 3000;

var API = 'add_your_API_here'

//Static Pages
app.use(express.static("public"));
app.use("/css", express.static(__dirname + "public/css"));

//set views
app.set("views", "./views");
app.set("view engine", "ejs");

//render ejs
app.get("", (req, res) => {
  res.render("index");
});

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/validate', (req, res) => {
  let email = req.query.email;
  let Url = `https://api.mailboxvalidator.com/v1/validation/single?key=${API}&email=${email}`

  request(
    { url: Url },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

//Listne to port 3000
app.listen(port, () => console.info(`Listning to port ${port}`));

How It Works?

After I input the email ID from my main application, it requests data from the mailboxvalidator API. Since the operation is happening on the server and not the browser, it doesn't throw a "CORS error," After the proxy server gets the output JSON from the original API, it displays it on /Validates endpoint.

Output-Json

Final Thought

It took me one month to troubleshoot the CORS error and try to find ways to solve it. But once I got some help and understood the concept, it became easier to solve it.

I hope it also helps you to solve this bug, and you don't have to be stuck for a significant amount of time to get your first project up and running.

See the Project Repo Here: Email Validator App

That’s it for today.

If you need further help, you can connect with me on Twitter

Check out Pomo.do

Read my other blogs:

Did you find this article valuable?

Support Arnab Ghosh by becoming a sponsor. Any amount is appreciated!