Angular 2 - 预检的响应具有无效的HTTP状态代码401

Chr*_*ris 5 cors preflight angular



我知道这里已经有很多相同的解决问题,
但不幸的是他们都没有帮助我:-(.

这里我的问题:
我尝试从我的localhost连接到服务器上的REST服务.它与FF REST插件一起工作正常,但我的应用程序导致以下错误:

我如何尝试获取我想要的数据:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我的服务器配置如下:

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
Run Code Online (Sandbox Code Playgroud)

我知道还有其他相同/类似的问题.但我仍然不知道该做什么或怎么做.如果有人可以帮我解决我的代码,我真的很感激!

Wes*_*zee 4

浏览器OPTIONS在执行您的 之前执行请求HttpGet,您需要添加一个与 具有相同路由的端点HttpGet,发出HttpOptions请求,从该端点删除身份验证并200 OK从中返回 a ,这应该可以解决您的问题。

  • 不是 Angular 正在执行 OPTIONS 请求,而是浏览器。 (2认同)