我的Angular应用程序在localhost:4200中运行,而我的Spring Boot应用程序在localhost:8080中运行。
当我从Angular应用发出春天的请求时,我可以看到json响应出现在网络选项卡中。但是我在控制台中收到此错误
CORS策略已阻止从源“ http://localhost:8080/getrep”访问“ http://localhost:4200”处的XMLHttpRequest:“ Access-Control-Allow-Origin”标头包含多个值“ http://localhost:4200” ,*',但只允许一个。
启动时的MT代码:
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@ConfigurationProperties(prefix="endpoint")
public class ReportController {
@Autowired
private static Environment env;
RestTemplate restTemplate;
static String serviceURL;
static Object response = null;
static String api_token = "<token>";
@GetMapping("/")
public String showcurrtime() {
return "Hello! The time on the server is:" + LocalDateTime.now();
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@GetMapping("/getrep")
public static Object getreports() {
serviceURL = "xyz";
try {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("X-Authorization", api_token);
headers.add("user-agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
response = restTemplate.exchange(serviceURL, HttpMethod.GET,entity,Object.class);
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
它的响应为
CORS策略已阻止从源“ http://localhost:8080/getrep”访问“ http://localhost:4200”处的XMLHttpRequest:“ Access-Control-Allow-Origin”标头包含多个值“ http://localhost:4200” ,*',但只允许一个。
在浏览器中,我在响应标题中看到了这一点。
Access-Control-Allow-Origin: http://localhost:4200, *
我该如何解决?