Open In App

What is Web CORS in HTML5 ?

CORS in HTML5 stands for Cross-Origin Resource Sharing. CORS is a mechanism that allows a website on one URL to request data from a different URL in the form of image, text, or even an API. This is an HTTP-header-based mechanism that limits the server to load resources from any other ports or domains other than itself. Let’s understand it with an example:

Explanation :



Origin header to the request :



Image of the Origin header in a request

Errors and the Browser Policy : 

CORS ERROR IMAGE

Fix the CORS error : 

We have to use a CORS middleware inside our Node.js application to fix this error from our server-side. That will allow us to change the access-control-allow-origin header of the response object sent from our server.

npm install express
npm install cors




// Import Express
const express = require('express');
  
// Create the Express App
const app = express();
  
// Import CORS
const cors = require('cors');
  
// Set the access-control-allow-origin header
// for all the responses sent from this URL
// Using the origin keyword
app.use(cors({ origin: 'http://desired.url' }));

Article Tags :