Angular 2 - Response for preflight has invalid HTTP status code 401

瘦欲@ 提交于 2019-12-07 06:05:44

问题




I know there a already lot of same solved issues here,
but unfortunately none of them helped me :-(.

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

  • OPTIONS http://.../my_REST_Service/ 401 (Unauthorized)
  • XMLHttpRequest cannot load http://.../my_REST_Service/.
    Response for preflight has invalid HTTP status code 401

How I try to get the data I want:

@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 like this:

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

I know there are other same/ similar solved issues. But I still do not know what to do or how to do it. I really appreciate it if someone can help me with my code!!


回答1:


"My Server is configured like this" — That's mostly irrelevent. Look at the error message: "Response for preflight has invalid HTTP status code 401"

It says nothing about any of the things you mentioned with Access-Control-Allow-Thing.

  • The browser is making an OPTIONS request to ask if a cross origin request is allowed.
  • The response says "Your username and password is wrong".

Since the browser hasn't received permission to make the cross origin request: It hasn't sent a username and password.

You need to find the code on your server that performs the authorisation and exclude OPTIONS requests from that test. Anybody should be able to make the OPTIONS request, not just people who have the username and password.




回答2:


The browser does an OPTIONS request before doing your HttpGet, you need to add an endpoint with the same route as the HttpGet, make that an HttpOptions request, remove auth from that endpoint and return a 200 OK from it and that should fix your issue.




回答3:


On the server side, if using Node.js you can consider authorizing all OPTIONS requests so browsers won't need authentication to check what methods are authorized on the server/REST API.

Consider code like:

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


来源:https://stackoverflow.com/questions/45297853/angular-2-response-for-preflight-has-invalid-http-status-code-401

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!