我正在尝试使用 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-允许来源感觉)。”
如果我从 Mozilla“RESTClient”发出请求,一切正常。 这是来自服务器的响应 header ,如果我从 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 请求的服务器响应 header :
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 和网络,但没有找到解决方案...
非常感谢!
最佳答案
这些 header 需要由服务器随响应一起发送。将它们与请求一起从客户端发送是没有意义的。
headers.append("Access-Control-Allow-Origin", "*");
headers.append("Access-Control-Allow-Credentials", "true");
如果您使用 withCredentials: true
,则 *
不足以满足 Access-Control-Allow-Origin
。服务器需要使用客户端请求的确切 URL(协议(protocol)、主机、端口)进行响应。
关于authentication - Angular 2 基本身份验证 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838941/