Arnab Ghosh
Arnab Ghosh

Arnab Ghosh

How to Bypass the CORS Error in Browser?

How to Bypass the CORS Error in Browser?

Learned a claver fix to bypass the CORS Error in Node.js

Arnab Ghosh's photo
Arnab Ghosh
ยทMar 27, 2022ยท

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • The Vanilla JS Approach
  • The Node.JS Approach
  • Final Thought

I started to learn coding aroung 2 months back from neog.camp.

Here, I did an interesting beginner-level Project, where I had to use an API to convert English to Klingon language.

As I was doing it, I learned the power of APIs and thought, what else can I build with APIs?

I am a content marketer by profession, and I have to verify prospects' emails from time to time.

I thought, why not create a web tool that helps me verify the prospects' emails?

It will be an excellent way to practice HTML, CSS, and JavaScript.

Little did I know, this small project would push me to learn more about Node.js.

The Vanilla JS Approach

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

Access-Control-error.png

I got stuck there for almost 2 weeks.

Then as I was reading the API documentation, there it was explained that we could use Node.JS to use the API.

Now, I had to learn Node.JS to create the tool.

The Node.JS Approach

When I started to create the logic, I tried to use the npm package in the public/app.js, which obviously did not work.

After I learned that "You can't use npm package outside the server"๐Ÿคฆโ€โ™‚๏ธ, I used the mailboxvalidator-nodejs package in the server.js, It was working in the server.

Mail-box-validator-working

But, the problem was, how do display the output on the website?

I couldn't do it. I tried multiple ways, but I could not.

It seems that this package was not meant to use different ways. Either that or I was missing something.

My situation was like this:

frustrated.png

I was on the verge of giving up.

Luckily I have people who can help.

I reached out to Harshit Saxena on discord, and he gave a unique way to solve the problem by using a proxy server.

Understanding the CORS Error

First of all, the Access-Control-Allow-Origin key is there to ensure the web application and the server match.

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 different domain origin from a third party server, let's say from arnabghosh.me to mailboxvalidator.com, it gives the CORS error, because the API has a header key that only allows requests from the same domain origin.

The code may look like this Access-Control-Allow-Origin: http://mailboxvalidator.com

Once the request is received by the browser, it cross-checks for the Access-Control-Allow-Origin value from the server. If the domain origin does not match, it throws the CORS error.

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

Did you find this article valuable?

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

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this