How Does the Access-Control-Allow-Origin Header Work?


In this tutorial, we will learn how access control allows the origin header to work.

Access-Control-Allow- Origin is a header for CORS. With CORS or cross-origin resource sharing, browsers can permit a website hosted at origin A to request resources from origin B.

Origin is a mix of port, hostname, and scheme, such as http://tutorialspoint.example.com:5000/, rather than just the hostname.

Here is an illustration of how this is put into practice −

  • I want to obtain resources from origin B, which is http://yoursite.com, and origin A:http://tutorialspoint.com.

  • The browser will deny my request and prevent me from accessing resources from yoursite.com to preserve your security.

  • Your origin B must inform the browser that it is acceptable for me to receive resources from your origin to permit origin A to access your resources.

Browsers permit origins to share resources due to CORS.

The key header for resource sharing between origins is Access-Control-Allow-Origin, though there are a few others. The browser is informed by these which origins are permitted to send requests to this server.

Who is required to configure Access-Control-Allow-Origin?

Consider the following example to determine who should set this header: You are looking at a website where songs can be seen and heard. The website surreptitiously tries to connect to your bank in the background.

Therefore, the bank must set the Access-Control-Allow-Origin header as part of the response to safeguarding its resources. Just keep in mind that this header must be set by the origin that is responsible for serving the resources.

What is CORS?

CORS, or Cross-Origin Resource Sharing, is a method that tells browsers that it is okay to use an additional origin by using extra HTTP headers.

Origin

The protocol, host, and port used to access a URL identify the origin of a piece of web content. If the scheme, host, and port are the same for two items, they can share the exact source.

When telling the browser to accept code from any origin to access a resource, the answer should say −

Access-Control-Allow-Origin: *

Non-simple requests

The network level of events can be a little more complicated than previously described. To determine whether the server will accept a “non-simple” request, the browser first makes a data-free “preflight” OPTIONS request. When either (or both), a request is not straightforward

  • using an HTTP verb besides getting or POST (e.g., PUT, DELETE)

  • using complex request headers (the only specific request headers are −

Accept, Accept-Language, Content-Language, and Content-Type (this is only straightforward if the value is text/plain, application/x-www-form-url encoded, or multipart/form-data) The browser sends the request if the server answers the OPTIONS preflight with response headers that match the non-simple verb and non-simple headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs). The browser would first conduct a preflight request if Site A wanted to send a PUT request for /somePage with a non-simple Content-Type value of application/json −

OPTIONS /somePage HTTP/1.1
Origin: http://siteA.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type

It should be noted that the browser automatically adds Access-Control-Request-Method and Access-Control-Request-Headers; you do not need to add these. For example, the successful response headers for this OPTIONS preflight are as follows −

Access-Control-Allow-Origin: http://siteA.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type

The behavior is the same as how a straightforward request is handled when sending the proposal (once the preflight is complete). In other words, if the preflight for a non-simple request is successful, it will be considered a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).

The browsers send the actual request:
PUT /somePage HTTP/1.1
Origin: http://siteA.com
Content-Type: application/json
{ "myRequestContent": "JSON is so great" }

And exactly like it would for a straightforward request, the server replies with an Access-Control-Allow-Origin −

Access-Control-Allow-Origin: http://siteA.com

Example

In the below example, we have created a server that runs on port 5000 in the localhost. In this application, we set the Access-Control-Allow-Origin header to tutorialspoint. If we communicate to the server from the tutorialspoint, then it will work fine. But if we try to communicate with any other domain, it will throw an error. We can’t send any get or post requests from other domains except tutorialspoint.com.

const express = require("express");
const app = express();
// Access-Control-Allow-Origin
app.use((req, res, next) => {
   res.setHeader("Access-Control-Allow-Origin", "https://tutorialspoint.com");
   res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept"
   );
   next();
});
app.get("/view", (req, res) => {
   res.send("Welcome to Tutorialspoint!");
});
app.listen(5000, () => console.log('Listening on port 5000'));

Trying to send a get request to localhost:5000/ from localhost:3000/.

fetch('http://localhost:5000/view')
.then(response => console.log(response));

Output


Change the headers to the following to fix this −

res.setHeader("Access-Control-Allow-Origin", "*");

Updated on: 06-Dec-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements