CORS Angular 和 SpringBoot - 请求被阻止

2024-04-04

我有一个问题,我似乎没有弄清楚。 我想从我的设备发送一个 http 请求

角度客户端:

const url = 'http://localhost:8080/api';
console.log(this.http.get(url).subscribe(data => this.greeting = data));

到 SpringBoot 后端,我使用 CORS 注释:

@CrossOrigin(origins = "http://localhost:4200/", maxAge = 3600)
    @RequestMapping("/api/")
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }

但我收到一个错误,它被阻止并始终将我重定向到登录。

Failed to load http://localhost:8080/api: Redirect from 'http://localhost:8080/api' to 'http://localhost:8080/login' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 

有办法改变吗?

我很感激任何有关此的提示或帮助。我想了解为什么会出现这个问题。


你的有错误RequestMapping,正如您所使用的@RequestMapping("/api/"),这将被评估为http://your_url/api//。您的控制器中不存在此类映射,因此它会给您 CORS Origin 错误。

只需删除尾随/ from @RequestMapping("/api/")这样它将是@RequestMapping("/api").

你的课程应该如下所示,

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class DemoController {

    @RequestMapping(value = "/api", method = RequestMethod.GET)
    public Map<String,Object> home() {
        Map<String,Object> model = new HashMap<String,Object>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello World");
        return model;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CORS Angular 和 SpringBoot - 请求被阻止 的相关文章

随机推荐