Angular Httpclient 有 CORS 错误,但没有获取

Angular Httpclient has CORS error vs but fetch not

我注意到我的 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 uses XMLHttpRequest。虽然 Fetch 可以执行 no-cors 请求,但 XMLHttpRequest API 不能。这就是为什么。

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

有了这个 header,获取 XML 文件的请求就不再是 'simple request',因此将执行 CORS 检查。

更多信息here

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

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