我正在尝试通过Webstorm使用Angular 5构建一个应用程序。我已经在后端设置了我的服务。当我尝试从postman或Rest客户端工具检索数据时,Webstorm提供的一切都是正常的。
但是当我试图从我的实际代码中获取数据时,angular说
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 我在我的java服务的后端添加了头文件,比如
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");我在出口课上的作用如下
constructor(private http: HttpClient) { }
login(username: string, password: string) {
console.log(username + '' + password);
const headers = new HttpHeaders().append('Content-Type', 'application/json')
const url = 'http://localhost:8080/../UserLogin';
return this.http.post(url, {'username': username, 'password': password} )
.subscribe(
(data: any) => {
console.log(data);
}
);
}当我检查来自chrome的Network Session的请求头时,我看到请求方法是options,并且没有请求数据。
我有点困惑为什么postman和webstrom的rest客户端运行得很好,而不是我的函数,第二个客户端是关于从Post转换为OPTIONS的请求方法
任何帮助都将不胜感激。
发布于 2018-04-28 03:29:41
您需要添加{ withCredentials: true }作为帖子的第三个参数。
return this.http.post(
url,
{'username': username, 'password': password},
{ withCredentials: true }
)
.subscribe(
(data: any) => {
console.log(data);
}
);发布于 2018-04-28 04:09:57
实际问题取决于Chrome如何评估CORS操作。
我从一个相对的帖子中找到了这个答案,这对我真的很有帮助
No 'Access-Control-Allow-Origin' header is present on the requested resource error
如果您安装了该扩展,一切都会恢复正常:
扩展的3小时浪费:P
https://stackoverflow.com/questions/50069033
复制相似问题