[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access
[英]No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed accesss
我已經從Angular http服務調用了Spring REST Web服務。 我正在調用get方法。 我正在跟蹤異常。
無法加載http://127.0.0.1:8080/SpringRestExample/rest/emp/dummy :對預檢請求的響應未通過訪問控制檢查:所請求的資源上沒有'Access-Control-Allow-Origin'標頭。 因此,不允許訪問源' http:// localhost:4200 '。
我在客戶端和服務器端添加了標頭,如下所示,但仍然存在錯誤。
客戶端:
let headers= new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type,application/json');
headers.append('Access-Control-Allow-Methods', 'GET');
headers.append('Access-Control-Allow-Origin', 'http://localhost:4200');
let options = new RequestOptions({ headers: headers });
this.http.get("http://127.0.0.1:8080/SpringRestExample/rest/emp/dummy",options).subscribe(data => {
console.log(data);
服務器端
httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
httpResponse.setHeader("Access-Control-Allow-Methods", "GET");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,'application/json'");
有人知道解決方案嗎?
刪除客戶端標頭並添加
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
您的服務器端代碼。
我有一個用於CORS的spring boot配置,並且工作正常:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "OPTIONS", "GET", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.