在Angular中,要解决CORS(跨域资源共享)问题,需要在服务端进行配置,同时也需要在Angular代码中进行相应的修改。
在服务端配置中,需要添加如下代码:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
在Angular代码中,可以使用HttpClientModule并添加如下代码:
import { HttpClientModule } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
this.httpClient.post(url, data, httpOptions).subscribe((res)=>{
console.log(res);
});
同时,也可以使用JSONP来解决CORS问题。例如:
this.jsonp.get(url).subscribe((res)=>{
console.log(res);
});