在Angular中,可以使用代理服务器来截断XHR响应。以下是一个解决方法的代码示例:
proxy.conf.json
的文件,并在其中定义代理服务器的配置:{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"changeOrigin": true
}
}
上述配置指定了将所有以/api
开头的请求代理到http://localhost:3000
。
angular.json
文件中,将proxy.conf.json
添加到serve
的options
中:"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
}
}
}
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('/api/data').subscribe(response => {
console.log(response);
});
}
}
上述代码中,我们使用HttpClient发送GET请求到/api/data
。由于我们在代理服务器配置中指定了将/api
开头的请求代理到http://localhost:3000
,因此实际请求将被代理到http://localhost:3000/api/data
。
通过以上步骤,你可以在Angular中使用代理服务器来截断XHR响应。