Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is CORS in JavaScript?

Fahad Farid

CORS is an HTTP-header that shows the domains, scheme, or ports from which a browser should be allowed to reload resources.

Example

Here is an example of a same-origin request:

Front-end at educative.io makes an XMLHttpRequest for educative.io/shot.json

To prevent attacks on websites, browsers restrict cross-origin HTTP requests from scripts. XMLHttpRequest and Fetch API follow the same-origin policy.

XMLHttpRequest and Fetch API can only process requests from the same origin where the application was loaded unless the other origin’s response includes the approriate CORS headers.

If a Javascript within the webpage is connected to access resources from a different server, you get the No Access-Control-Header-Present error. This means that you do not have access to load resources from that server. In the image above, you can see that a page from educative.io tries to load the image from EducativeImages.io. If Access-Control-Allow-Originthe header that lets the app know that you can allow resources to be loaded from this particular website is allowed within the header, only then will the image be loaded on the webpage; else, an error will be generated.

To correctly use the CORS policy in JavaScript, you can do one of the following:

1. Modify the header

In your get request, add the following to the header in the app.get function:

res.header("Access-Control-Allow-Origin", "true");

You will also need to add the following to the response:

crossorigin:true

2. Installing CORS

You can add the following code to your code:

const cors = require('cors');
app.use(cors());

You will, however, have to install CORS on your machine before you can use this. You can install it by running:

npm i cors

3. Using Express

You can use CORS with express by adding the following to your code:

const express = require('express')
const app = express()
app.use(cors())

RELATED TAGS

javascript

CONTRIBUTOR

Fahad Farid
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring