Fulfilling a cross-domain request with an authentication header

First of all, the server (not mine) returns the following headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

I am trying to figure out how to submit a request to a site using an authentication token. I am running the code on a local Apache server.

This is my code:

function get_data(){
    var url = '$URL';
    var x = new XMLHttpRequest();
    x.open("GET", url, true)
     if (x.readyState == 4 && x.status == 200) {
        var responseText = x.responseText;
        console.log(responseText)
        };
    x.setRequestHeader("Authentication", "Bearer $TOKEN");
    x.withCredentials = true
    x.send()
}

The console returns:

XMLHttpRequest cannot load $ URL. The response to a pre-flight request is not an access control check: there is no “Access-Control-Allow-Origin” header present on the requested resource. Origin ' http: // localhost ' is therefore not allowed access. The response had an HTTP status code of 403.

, . x.setRequestHeader("Authentication", "Bearer $TOKEN");, (, ). , ?

, :

Request URL:$serverurl
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:$ipaddress
Response Headers
view source
Cache-Control:no-cache
Connection:close
Content-Type:text/html
Request Headers
view source
Accept:"*/*"
Accept-Encoding:gzip, deflate, sdch
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:authentication
Access-Control-Request-Method:GET
Connection:keep-alive
Host:$host
Origin:http://localhost
Referer:http://localhost/mv.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
+4
1

GET OPTION, , "" ( , ..).

(), . , .

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, OPTIONS

: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Methods

403 , , , 403 . , api XHR.

-1

Source: https://habr.com/ru/post/1626170/


All Articles