【发布时间】:2016-07-21 02:17:01
【问题描述】:
我正在尝试将 basic authentification 添加到我的 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)
);
}
我希望看到的是带有 Authorizationheader 的 GET 请求。
但我首先看到的是带有此标题的 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?
谢谢。
【问题讨论】:
-
确保有一个斜杠,如stackoverflow.com/a/50062221/6748184中所述