Fix The CORS Error From Frontend
When developers start integrating APIs on the frontend and if frontend and backend(APIs) running on a different domain/subdomain/port/ then we face a CORS issue.
CORS —
It is an HTTP-header-based implementaion. browsers uses mechanism of preflight request . in preflight request to server it checks that ther server will permit actual request or not. if server does not permit than browser shows CORS error.
Ways to Fix it from Frontend
In a real way, CORS should be enabled from the backend server itself by setting correct HTTP-headers and allowing concerned domains.
but sometimes we want to bypass this check from the frontend itself. in this case, we can use the below-mentioned fixes.
- Using ModHeader Chrome Extension
- By Creating a mocked server
Using ModHeader-
- install ModHeader extension in the browser. just search modHeader extension and add it to your browser.
2. Add response header, and set “Acess-Control-Allow-Origin” to “*” then refresh your web page. it will start fetching data without any CORS error.
By Creating a mocked server
Another solution is to create a simple express server with node and set
“Acess-Control-Allow-Origin” to “*” and from there redirect fetch request to the server.
Create a folder in your system and add a file app.js inside it and put the below code inside this file.
Changes need to make in your frontend code
Call API with base URL — http://localhost:3000
your API call will look like http://localhost:3000/endpointsofAPI
and in app.js file update “APIBaseURL” this with actual base URL of your API.
Code
const express = require(‘express’);
const request = require(‘request’);
const app = express();
app.use((req, res, next) => {
res.header(‘Access-Control-Allow-Origin’, ‘\*’);
next();
});
app.use(‘/’, (req, res) => {
const endPoint = req.url;
console.log(endPoint)
request(
{ url: \`APIBaseURL{endPoint}\` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
console.log(error)
return res.status(500).json({ type: ‘error’, message: error?.message });
}
res.json(JSON.parse(body));
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(\`listening on ${PORT}\`));
install packages-
Create a package.json file with same level of app.js and put below code
{
“name”: “server”,
“version”: “1.0.0”,
“description”: “”,
“main”: “app.js”,
“scripts”: {
“test”: “echo \\”Error: no test specified\\” && exit 1"
},
“author”: “Anil Verma”,
“license”: “ISC”,
“dependencies”: {
“express”: “⁴.17.1”,
“request”: “².88.2”
}
}
Running Server —
open terminal and run command
npm i
once the above command completes installing packages then run the below command
node app.js
After that refresh your webpage, it will start fetching data without any CORS error.
Happy Coding…