Angular Httpclient有CORS错误vs,但fetch没有



我注意到我的angular应用程序中存在跨域问题。

如果我对xml文件请求使用fetch方法,它会起作用。

@Component({
selector:    'app-xml',
templateUrl: './app-xml.component.html'
})
export class HeroListComponent implements OnInit {
constructor( private httpClient: HttpClient) {}
getXml(){
fetch(url).then((response:any) => {
return response.text();
}).then((text:any) => { console.log(text)})
}
}

但如果我使用angular HttpClient,它会抛出一个跨域Xmlhttprequest错误。

@Component({
selector:    'app-xml',
templateUrl: './app-xml.component.html'
})
export class HeroListComponent implements OnInit {
constructor( private httpClient: HttpClient) {}
getXml(){
httpClient.get<any>(url).subscribe((response:any) => {
console.log(text)
})
}
}

为什么?

因为Fetch API和XMLHttpRequest API具有不同的功能。在这种情况下,Angular使用XMLHttpRequest。虽然Fetch可以执行无代码请求,但XMLHttpRequest API不能执行。这就是为什么。

如果使用HttpClient,angular将默认添加一个值为application/json的Content-Type标头

有了这个头,获取XML文件的请求就不再是一个"简单的请求",因此将执行CORS检查。

更多信息点击这里

尝试按如下方式指定responseType,这应该将Content-type标头设置为text/plain并阻止CORS检查。这可能是您想要的,因为您试图检索xml文件,而不是json数据。

httpClient.get<any>(url, {responseType : 'text'})

最新更新