【发布时间】:2017-04-11 20:36:47
【问题描述】:
我正在尝试使用 Angular 对具有基本 HTTP 身份验证的“普通”Api 进行简单的 HTTP-Api-Call。 我现在的问题是,浏览器说:“Quellübergreifende (Cross-Origin) Anfrage blockiert: Die Gleiche-Quelle-Regel verbietet das Lesen der externen Ressource auf "...". (Grund: CORS-Kopfzeile 'Access-Control- Allow-Origin' fehlt)。”
如果我从 Mozilla“RESTClient”发出请求,一切正常。 这是来自服务器的响应标头,如果我从 RESTClient 发出请求:
Status Code: 200 OK
Age: 0
Cache-Control: proxy-revalidate, proxy-revalidate
Connection: Keep-Alive
Content-Length: 698
Content-Type: text/xml; charset=UTF-8
Date: Mon, 28 Nov 2016 06:52:57 GMT
access-control-allow-credentials: true
access-control-allow-origin: *
所以,如您所见,'access-control-allow-origin:'-Header 已设置...
这是我的 angular2 方法:
// hole die Header für die Api-Aufrufe
getHeaders() {
let username = this.variables.getUsername();
let password = this.variables.getPassword();
let headers = new Headers();
//headers.append("Content-Type", "text/xml");
headers.append("Access-Control-Allow-Origin", "*");
headers.append("Access-Control-Allow-Credentials", "true");
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
headers.append("Content-Type", "application/x-www-form-urlencoded");
let options = new RequestOptions({headers: headers});
console.log(JSON.stringify(options));
return options;
}
// Api-Calls
getStatus() {
return this.http.get(this.variables.getUrl() + 'status2.html', this.getHeaders())
//return this.http.get(this.localURL + 'status.json')
.map((res: Response) => res.json())
.catch(this.handleError);
}
这里是 Angular2 请求的服务器响应头:
OPTIONS /api/status2.html HTTP/1.1
Host: ...
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Origin: http://localhost:3000
Connection: keep-alive
有人可以指导我正确的方向或给我正确的答案吗? 我搜索了 stackoverflow 和网络,但没有找到解决方案...
非常感谢!
【问题讨论】:
-
错误信息是否有更多细节?
-
这是 Firefox(德语)中的全部错误:Quellübergreifende (Cross-Origin) Anfrage blockiert: Die Gleiche-Quelle-Regel verbietet das Lesen der externen Ressource auf '...'。 (Grund:CORS-Kopfzeile 'Access-Control-Allow-Origin' fehlt)。所以 Firefox 不允许我认为的请求......但我不明白为什么......
标签: authentication angular cors