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

Posted

技术标签:

【中文标题】尝试从 Github API + Spring Boot 获取到 Angular 时出现 CORS 错误【英文标题】:CORS error when trying to fetch from Github API + Spring Boot to Angular 【发布时间】:2018-06-23 04:39:24 【问题描述】:
@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)时,它会给出预期的响应。

我该如何纠正这个问题?

谢谢。

【问题讨论】:

github.com/angular/angular-cli/wiki/stories-proxy @JBNizet 我尝试在 proxy.config.json 中添加 "/getrepo/*": "target": "http://localhost:8080", "secure": false, "logLevel": "debug" 并更改了启动脚本。还是不行..我做错了吗? 如果你还在向http://localhost:8080/getrepo/dasunpubudumal发送请求,那么这是没用的。重点是将请求发送到http://localhost:8080/getrepo/dasunpubudumal,或者只是/getrepo/dasunpubudumal。这样您就不再需要 CORS。 【参考方案1】:

得到这个工作。显然getRepository() 函数不需要跨域注解。

【讨论】:

以上是关于尝试从 Github API + Spring Boot 获取到 Angular 时出现 CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章