尝试从Github API + Spring Boot获取到Angular时出现CORS错误

时间:2018-01-14 08:35:32

标签: angular spring-boot cors github-api

@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)时,它会给出预期的响应。

我该如何纠正?

谢谢。

1 个答案:

答案 0 :(得分:0)

有这个工作。显然getRepository()函数不需要交叉原点注释。