Angular 2 - Preflight response has invalid HTTP 401 status code



I know that there are already many similar problems,
but, unfortunately, none of them helped me :-(.

Here is my problem:
I try to connect from my localhost to my REST service on the server. It works fine with the FF REST plugin, but my application leads to the following errors:

How am I trying to get the data I need:

@Injectable()
export class ModelsComponent implements OnInit {

    private restRoot = 'http://.../my_REST_Service';
    private data;

    constructor(private http: Http) { }

    ngOnInit() {
        this.getModels().subscribe(res => {
            this.data = res; 
            console.log(this.data);
        });
    }

    authHeaders() {
        let username: string = 'xxxx';
        let password: string = 'xxxx';

        let token: string = btoa(username + ":" + password);

        let headers: Headers = new Headers();
        headers.append('Access-Control-Expose-Headers', 'Authorization');
        headers.append('Authorization', 'Basic ' + token);
        headers.append("Access-Control-Allow-Origin", "http://localhost:4200/");
        headers.append("Access-Control-Allow-Methods", "*");
        headers.append("Access-Control-Allow-Headers", "Accept,Accept-Charset,Accept-Encoding,Accept-Language,Authorization,Connection,Content-Type,Cookie,DNT,Host,Keep-Alive,Origin,Referer,User-Agent,X-CSRF-Token,X-Requested-With");
        headers.append("Access-Control-Allow-Credentials", "true");

        return headers;
    }

    getModels(): Observable<any> {
        return this.http.get(this.restRoot, {
                    headers: this.authHeaders(), 
                    withCredentials: true        <- from a similar issue
               }).map(res => res.json());
    }
}

My server is configured as follows:

Header set Access-Control-Allow-Origin "http://localhost:4200"
Header set Access-Control-Allow-Headers "Accept,Accept-Charset,Accept-Encoding,Accept-Language,Authorization,Connection,Content-Type,Cookie,DNT,Host,Keep-Alive,Origin,Referer,User-Agent,X-CSRF-Token,X-Requested-With"
Header set Access-Control-Allow-Methods "*"
Header set Access-Control-Allow-Credentials "true"   
Header set Access-Control-Expose-Headers "Authorization"       <- from a similar issue

, / . , . , - !

+4
3

HttpGet OPTIONS, , HttpGet, HttpOptions, auth 200 OK, .

+3

" " - . : " HTTP 401"

, Access-Control-Allow-Thing.

  • OPTIONS, , .
  • : " ".

: .

, , OPTIONS . OPTIONS, , .

+2

On the server side, if you use Node.js, you can allow authorization of all OPTIONS requests so that browsers do not need authentication to check which methods are allowed on the server / REST API.

Consider a code like:

if (req.method === 'OPTIONS') {
    res.status(200).end();
} else {
    next();
}
+1
source

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


All Articles