【发布时间】:2019-11-17 12:20:15
【问题描述】:
我正在尝试在我的 Spring Boot 应用中启用 CORS,但它根本不起作用。
我试过了
-
@CrossOrigin注解 - CORS with spring-boot and angularjs not working
- 还有这个https://spring.io/guides/gs/rest-service-cors/
我目前不知道如何解决此问题,也不知道 CORS 无法正常工作的问题是什么。
我的代码
控制器
@RestController
public class DbController {
@Autowired
private IDAO conn;
@CrossOrigin
@GetMapping("/foo")
public List<Foo> getFoo() {
return conn.getFooFromDao();
}
}
DAO
@Repository
public class DaoImpl implements IDAO {
@Autowired
private JdbcTemplate temp;
public List<Foo> getFooFromDao() {
List<Foo> data = new ArrayList<>();
String sql = "SELECT fooName FROM BigFoo ORDER BY fooName ASC;";
data.addAll(temp.query(sql, new BeanPropertyRowMapper(BigFoo.class)));
return data;
}
}
预期:
我希望通过 any 方法从 any 源/域访问我的控制器。
实际:
我的控制器不能从任何源/域访问。它给我的 Angular 前端一个错误:
编辑:我在前端的错误
在 'localhost:8080/foo' 从源访问 XMLHttpRequest 'http://localhost:4200' 已被 CORS 策略阻止:跨源 请求仅支持协议方案:http、data、chrome、 chrome 扩展,https。
第二次编辑:
这是我在 Angular(前端)中的代码:
服务
getFoo() {
return this.http.get("localhost:8080/foo");
}
我正在使用来自import { HttpClient } from "@angular/common/http"; 的HttpClient
我还通过将 URL 复制并粘贴到我的浏览器中来验证该 URL 在该服务方法中是否有效。它确实返回了 JSON,它排除了错误 URL 或拼写错误的可能性。
【问题讨论】:
-
对不起,我不明白你在说什么。什么是 Spring In Action 5?
-
你的spring tomcat控制台有没有收到任何信号,我的意思是请求到达了吗?并告诉我你是如何使用这项服务的?到现在为止,你做得对。
-
不,我的 spring 控制台中没有任何响应。它只是在我的浏览器中给了我错误,而没有响应它在我的 IntelliJ 控制台中击中它。另外,“使用服务”是什么意思?
-
错字;你需要做
this.http.get("http://localhost:8080/foo")而不是this.http.get("localhost:8080/foo")。也就是说,您必须包含http://部分。 -
您需要在 Angular 应用程序的 url 前面输入协议名称“http://”:例如this.http.get("http://localhost:8080/foo")
标签: java spring spring-boot cors