当我尝试从Angular 5中访问post service时,我遇到错误了
无法加载资源:服务器的响应状态为403 (禁止)访问XMLHttpRequest 原产地的“ https://xxxx/xxxx/services/exportVarianceHome” “ http://localhost:4200”已被CORS政策屏蔽:
对预检请求的响应未通过访问控制检查:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。
以下是我在Angular 5中的拦截器配置
import { HttpClient} from '@angular/common/http';
constructor(private httpClient:HttpClient){
getLookupDetails();
}
getLookupDetails(){
this.httpClient.get(this.servicsUrl).subscribe(
(data:any) => {
console.log("JSON Response " + JSON.stringify(data));
}
)
}
和Angular Post呼叫
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication(scanBasePackages = {"com.controller.gtm"})
public class BrokerValidationApplication extends SpringBootServletInitializer implements WebMvcConfigurer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BrokerValidationApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(BrokerValidationApplication.class, args);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println(">=== Inside Cors Orgin Mapping addCorsMappings ===>");
registry.addMapping("/services/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(4800);
}
}
以及服务器端(SpringBoot)的跨源设置
{{1}}