[英]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.