尝试从 Github API + Spring 获取时出现 CORS 错误引导至 Angular

CORS error when trying to fetch from Github API + Spring Boot to Angular

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(method = RequestMethod.GET, value = "/getuser/{username}")
public User getUser(@PathVariable String username) {
    restTemplate = new RestTemplate();
    headers = new HttpHeaders();
    headers.set("User-Agent", "profile-analyzer");
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
    ResponseEntity<User> user = restTemplate.exchange("https://api.github.com/users/"+ username +
            "?client_id=" + client_id + "&client_secret=" + client_secret,
            HttpMethod.GET, entity, User.class);
    return user.getBody();
}

我在这里(上面的代码)要做的是从 Github API 获取一些数据,它工作正常,我可以将数据获取到 Angular ( 运行 在端口 4200 上)。

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(method = RequestMethod.GET, value = "/getrepo/{username}")
public Object getRepository(@PathVariable String username) {
    restTemplate = new RestTemplate();
    headers = new HttpHeaders();
    headers.set("User-Agent", "profile-analyzer");
    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
    ResponseEntity<Object> repository = restTemplate.exchange("https://api.github.com/users/"+ username +
                    "/repos" + "?client_id=" + client_id + "&client_secret=" + client_secret,
            HttpMethod.GET, entity, Object.class);
    return repository;

}

但是当我在同一个控制器中执行此操作(上面的代码)时,当我尝试从 Angular 服务器(端口 4200)访问数据时,我的浏览器会显示类似这样的内容。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/getrepo/dasunpubudumal. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).

我所做的是我刚刚更改了 Github 的端点,我正试图从中使用数据。

但是,当我直接访问 spring(即 http://localhost:8080/getrepo/dasunpubudumal)的端点时,它给出了预期的响应。

我该如何纠正?

谢谢。

成功了。显然 getRepository() 函数不需要跨源注释。