Access-Control-Allow-Origin error with Xmlhttprequest()

Asked

Viewed 11,983 times

1

Hello, I’m having the following mistake:

No 'Access-Control-Allow-Origin' header is present on the requested Resource.

Already researched and the solution I find is to add:

        request.setRequestHeader('Access-Control-Allow-Origin', '*');

However, even then the error persists. If I run the application with Cors turned off, it works normally. Can anyone help me?

var request = new XMLHttpRequest();

    request.open('GET', 'https://www.URLAPI.com/api/v3/PARAMETRO);

    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    request.setRequestHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

    request.setRequestHeader('Content-Type', 'application/json'); //Obrigatorio API
    request.setRequestHeader('access_token', 'MEUTOKEN'); //Obrigatorio API

    request.onreadystatechange = function () {
        if (this.readyState === 4) {
            if(request.status === 200){
            console.log('Status:', this.status);
            console.log('Headers:', this.getAllResponseHeaders());
            console.log('Body:', this.responseText);

                                console.log(request);

            }else{
                console.log("Erro");
                console.log(request);
            }
        }
    };

    request.send(); 

Angular Project 7 (WEB). I can only access the data I need when I run Chrome with CORS disabled.

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
  • Have to release the CORS on the server, that’s where you changed?

3 answers

2


Solution:

  • As the API server I was working on was not returning the CORS protocol and the browser was performing communication blocking, after much searching I found the solution on the link: Using Proxy Server to perform switching.

Link to the server that handles CORS

This intermediary handles the CORS protocol and can communicate with the API I need. The code is:

var request = new XMLHttpRequest();

request.open('GET', 'https://cors-anywhere.herokuapp.com/https://www.URLAPI.com/api/v3/PARAMETRO);


request.setRequestHeader('Content-Type', 'application/json'); //Obrigatorio API
request.setRequestHeader('access_token', 'MEUTOKEN'); //Obrigatorio API

request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if(request.status === 200){
        console.log('Status:', this.status);
        console.log('Headers:', this.getAllResponseHeaders());
        console.log('Body:', this.responseText);

                            console.log(request);

        }else{
            console.log("Erro");
            console.log(request);
        }
    }
};

request.send(); 
  • I tested the same code with another API and without the intermediary, and it worked correctly. I mean, the API does not work with the CORS SECURITY protocol.

0

"With the implementation of CORS one domain allows communication with another free form, independent of the call method (GET, POST, PUT or DELETE) as long as the target domain has specified this type communication.

Usually this setting is done on the API side and each framework has its configuration form. The important part is the inclusion of the Access-Control-Allow-Origin in the API reset header.

So, in a very simple scenario, your JS client application in dev.meudominio.com.br requests the API (usually in a AJAX call) for the.meudominio.com.com server. The API response should include Access-Control-Allow-Origin in the response header: http://dev.meudominio.com.br making it clear to the browser that it accepts requests originating only from this domain."

https://medium.com/@alexandremjacques/understanding-o-Cors-parte-8331d0a777e1

See the request example:

GET /recurso.php HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
Accept: application/json, text/plain, */*
Referer: http://dev.meudominio.com.br/
Origin: http://dev.meudominio.com.br/

And the API response model:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Wed, 20 Nov 2013 19:36:00 GMT
Server: Apache-Coyote/1.1
Content-Length: 35
Connection: keep-alive
Access-Control-Allow-Origin: http://dev.meudominio.com.br

If the content of Origin is identical to that of Access-Control-Allow-Origin communication is permitted by the browser.

0

I was doing a GET and jQuery worked and my Xmlhttprequest didn’t. I was angry, but I found out what was happening by going into jQuery’s code. So, for those who have this problem I managed to solve adding in headers

request.setRequestHeader('Accept', '*/*');

It was just THAT! And I had to remove the following codes (I don’t know why)

request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Access-Control-Allow-Origin', '*');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.