请求 http.GET 时发送的 Angular2 OPTIONS 方法[重复]

2024-04-16

我正在尝试添加基本身份验证 https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side到我的 angular2 应用程序。

public login() {
    // Set basic auth headers
    this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + this.password));

    console.log('username', this.username)
    console.log('password', this.password)
    console.log(this.defaultHeaders)

    // rest is copy paste from monbanquetapiservice
    const path = this.basePath + '/api/v1/development/order';        

    let req = this.http.get(path, { headers: this.defaultHeaders });
    req.subscribe(
        _ => { },
        err => this.onError(err)
    );
}

我期望看到的是带有以下内容的 GET 请求Authorization我放置的标题。

但我首先看到的是OPTIONS与此标题:

OPTIONS /api/v1/development/order HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
Access-Control-Request-Headers: authorization, content-type
Accept: */*
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6,fr;q=0.4

由于我的服务器不允许OPTIONS在此网址上,我收到错误。

我知道某些方法(如 PUT 或 POST)首先发送 OPTIONS 方法来预检请求,但 GET 不会。

为什么angular2的http先发送一个OPTIONS?

Thanks.


这就是 CORS 的工作方式(使用跨域请求时)。通过 CORS,远程 Web 应用程序(此处为 mydomain.org 域)可以通过一组特定标头来选择是否可以处理请求。

CORS 规范区分了两种不同的用例:

  • 简单的请求。如果我们使用 HTTP GET、HEAD 和 POST 方法,则适用此用例。对于 POST 方法,仅支持具有以下值的内容类型:text/plain、application/x-www-form-urlencoded 和 multipart/form-data。
  • 预检请求。当“简单请求”用例不适用时,将发出第一个请求(使用 HTTP OPTIONS 方法)来检查在跨域请求的上下文中可以执行哪些操作。

发送 OPTIONS 请求的不是 Angular2,而是浏览器本身。这与 Angular 无关。

想了解更多详情,你可以看看这篇文章:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/ http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

请求 http.GET 时发送的 Angular2 OPTIONS 方法[重复] 的相关文章

随机推荐