Angular 2 Basic Authenticatin CORS

I am trying to do a simple HTTP Api-Call with Angular in a “regular” Api with basic HTTP authentication. My problem is that the browser says: "Quellübergreifende (Cross-Origin) Anfrage blockiert: Die Gleiche-Quelle-Regel verbietet das Lesen der externen Ressource auf" ... ". (Grund: CORS-Kopfzeile" Access-Control- Allow -Origin 'fehlt).

If I make a request from Mozilla "RESTClient", everything will be fine. This is the response header from the server if I make a request from RESTClient:

Status Code: 200 OK
Age: 0
Cache-Control: proxy-revalidate, proxy-revalidate
Connection: Keep-Alive
Content-Length: 698
Content-Type: text/xml; charset=UTF-8
Date: Mon, 28 Nov 2016 06:52:57 GMT
access-control-allow-credentials: true
access-control-allow-origin: *

So, as you can see, the header is set to "access-control-allow-origin:" - Header ...

This is my angular2 method:

// hole die Header für die Api-Aufrufe
    getHeaders() {
        let username = this.variables.getUsername();
        let password = this.variables.getPassword();
        let headers =  new Headers();
        //headers.append("Content-Type", "text/xml");
        headers.append("Access-Control-Allow-Origin", "*");
        headers.append("Access-Control-Allow-Credentials", "true"); 
        headers.append("Authorization", "Basic " + btoa(username + ":" + password));
        headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        headers.append("Content-Type", "application/x-www-form-urlencoded");
        let options = new RequestOptions({headers: headers});
        console.log(JSON.stringify(options));
        return options;
    }

    // Api-Calls    
    getStatus() {
        return this.http.get(this.variables.getUrl() + 'status2.html', this.getHeaders())
        //return this.http.get(this.localURL + 'status.json')
            .map((res: Response) => res.json())
            .catch(this.handleError);
    }

Here is the Server Header answer for the Angular2 request:

OPTIONS /api/status2.html HTTP/1.1
Host: ...
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Origin: http://localhost:3000
Connection: keep-alive

- ? stackoverflow , ...

!

+4
1

. .

    headers.append("Access-Control-Allow-Origin", "*");
    headers.append("Access-Control-Allow-Credentials", "true"); 

withCredentials: true, * Access-Control-Allow-Origin. URL (, , ), .

+3

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


All Articles