No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Problem:

When trying to get resource located on server, we often get this error:

Access to XMLHttpRequest at ‘http://server-URL/video’ from origin ‘https://www.front-end-client-url.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

11

This error is different from the error which you get while trying to access resource located on local file system using file:/// using:

xmlhttp.open(“GET”, “test.xml”, true)

and you are getting below error:

Access to XMLHttpRequest at ‘file:///D:/test.xml‘ from origin ‘null’ has been blocked by CORS policy.

Its solution is provided here -> Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https, isolated-app.

Solution:

On the server side, we need to add these headers to make the browser to allow server-url to return data at client side.

Whatsoever method being called on the server side, we have to add headers like this :

app.get("/getUrl", function (req, res) {
   const headers = {
      "other-header": ‘header-value’,
       ---- 

      'Access-Control-Allow-Origin': 'https://www.front-end-client-url.com',
      'Access-Control-Allow-Methods':'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers':'Origin, Content-Type, Accept'
   };
   res.writeHead(200, headers);

// other code to return response });
Other solution is to develop applications where frontend and backend are hosted on same URL and become parts of same application. For example using Visual Studio template we can create a React UI app with Dotnet Core as backend so here there will be no CORS issue by as the Dotnet core application will contain the React client-app inside it and will run it together.

Understanding:

Assuming there a server-application that is hosted at http://localhost:8000/video

& your front-end/consumer application running on https://localhost:5002

When front-end app calls the server-api app, then by default the server returns the request but browser intercepts that request and stops the client app from getting it.

So we get the below error in our browser:

Access to XMLHttpRequest at ‘http://localhost:8000/video’ from origin ‘https://localhost:5002’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Terms to understand:

a–  Origin – the domain on which the application is hosted.

           In our example Origin of front-end app is https://localhost:5002 and 

           Origin of server-app is http://localhost:8000

      bCross-Origin – If one app at one Origin is making any call to any other Origin, it’s called cross-origin

      cAllow-Origin – Means server is allowing other Origin to make calls inbetween.

      d Resource-sharing – Means the Data that server is providing, which may be some text/image/json or any other allowed type.

      eHTTP-header – The headers value that are passed with a request. Eg :

            Connection: keep-alive 

            Content-Type: “video/mp4”

Cross-Origin Resource Sharing (CORS) is an HTTP header based system that allows a server running on Origin1 to send resources on browser that is running on any other Origin2.

Example: The browser is running URL – https://front-end-client-url.com and server is running on https://server-url.com

So, when response is returned from server then browser will give error that the XMLHttpRequest at http://server-url.com from origin https://www.front-end-client-url.com has been blocked by CORS policy.

To make a call between these cross-origin URLs we should let the server know that the requesting URL is permitted to communicate. To do that programmatically we need to set-up headers in the server response.

These headers are:

    a- Access-Control-Allow-Origin: it tells which Origin are allowed. Its value can be a single URL or multiple, to make it allowed for all the Cross-            origin requests we can set its value to ‘*’, which essentially makes it venerable to CORS attacks, so its not recommended.

   b- Access-Control-Allow-Methods: It talks about the allowed method, for example POST & GET only

   c- Access-Control-Allow-Headers: It talks about the allowed headers that can be sent in request by the front-end or the client application.

 
CORS also have a system by which browsers make a testing request called “preflight” request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request.
 
For “preflight” requests the browser first sends an HTTP request using the OPTIONS method to the resource on the other origin.  Suppose we have to make a post request to the server of cross-origin so we can send a preflight request with header Access-Control-Request-Method: POST, which essentially means we are checking whether the server is ok with our POST request or not.
 
If it returns the header with :
Access-Control-Allow-Origin: https://front-end-client-url.com

it means,  http://front-end-client-url.com can make a POST call to the http://server-url.com . Otherwise there may be the CORS error

The response to it is like :

HTTP/1.1 204 No Content
……other headers……
Access-Control-Allow-Origin: https://front-end-client-url.com
Access-Control-Allow-Methods: POST, GET, OPTIONS

Quiz time:

Now if you have understood above details about how CORS and Headers work, you should be able to answer below question :

Q: After setting these below headers in the server method of your app, if you try to make a DELETE request, will it be allowed by CORS ?

'Access-Control-Allow-Origin': 'https://www.front-end-client-url.com',
'Access-Control-Allow-Methods':'GET, POST, OPTIONS',
'Access-Control-Allow-Headers':'Origin, Content-Type, Accept'

Answer – 

No, As the headers are allowing only “GET, POST, OPTIONS” methods so when trying with Delete method, it will again give error : Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.

Access-Control-Allow-Methods

Look at two request in the network tab, one is actual and other is a preflight request.

Response of preflight request is below :

Preflight request

Please notice the headers – Access-Control-Request-Method: DELETE in request

 &

 Access-Control-Allow-Methods: Get, Post, Options in response

 So to solve it we need add DELETE in the allowed methods list as :

'Access-Control-Allow-Methods':'GET, POST, DELETE, OPTIONS'
 app.get("/getUrl", function (req, res) {
    const headers = {
        "other-header": ‘header-value’,
         ---- 
       'Access-Control-Allow-Origin': 'https://www.front-end-client-url.com',
       'Access-Control-Allow-Methods':'GET, POST, DELETE, OPTIONS',
       'Access-Control-Allow-Headers':'Origin, Content-Type, Accept'
    };
    res.writeHead(200, headers);
  // other code to return response
});

After doing it, the DELETE call should also start working.

More from Node/Javascript:

Natalie Harris
With references from Alan Plang
132
Kyle Aniston
With references from Alan Plang
75
Kyle Aniston
With references from StackOverflow
381
Mike Morgan
With references from StackOverflow
105
Mike Morgan
Forwared by QwertyBot
560
Mike Morgan
Forwared by QwertyBot
1.4k
Kyle Aniston
Forwared by Alan Plang
1.0k

Leave a Reply

Your email address will not be published. Required fields are marked *