CORS Angular 和 SpringBoot - 请求被阻止 [英] CORS Angular and SpringBoot - request blocked
问题描述
我有一个我似乎没有弄清楚的问题.我想从我的
I have a problem that I don't seem to figure out. I want to send a http request from my
Angular 客户端:
Angular client:
const url = 'http://localhost:8080/api';
console.log(this.http.get(url).subscribe(data => this.greeting = data));
到我使用 CORS 注释的 SpringBoot 后端:
to SpringBoot backend where I use CORS annotation:
@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;
}
但我收到一个错误,它被阻止并一直重定向我登录.
but I'm getting an error that it's blocked and redirects me to login all the time.
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.
有办法改变吗?
我感谢任何有关此的提示或帮助.我想了解为什么会出现这个问题.
I appreciate any hint or help regarding this. I would like to understand why this problem is happening.
推荐答案
您的 RequestMapping
有错误,因为您使用了 @RequestMapping("/api/")
,这将被评估为 http://your_url/api//
.您的控制器中不存在此类映射,因此它会给您带来 CORS Origin 错误.
You have error in your RequestMapping
, as you have used @RequestMapping("/api/")
, this will be evaluated as http://your_url/api//
. Such mapping is not present in your controller, hence it is giving you CORS Origin error.
只需从 @RequestMapping("/api/")
中删除尾随的 /
使其成为 @RequestMapping("/api")
>.
Just remove trailing /
from @RequestMapping("/api/")
so that it will be @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;
}
}
这篇关于CORS Angular 和 SpringBoot - 请求被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!