I am trying to enable CORS in my Spring Boot app, but it is not working at all.
I have tried
@CrossOrigin
annotation- CORS with spring-boot and angularjs not working
- And this https://spring.io/guides/gs/rest-service-cors/
I have no clue how to fix this at this point in time, nor what the issue is with CORS not working.
My code
Controller
@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;
}
}
Expected:
I want my controller to be accessible from any origin/domain with any method.
Actual:
My controller is not accessible from any origin/domain. It gives my Angular frontend an error:
EDIT: My error in the frontend
Access to XMLHttpRequest at 'localhost:8080/foo' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Second edit:
This is my code in Angular (frontend):
Service
getFoo() {
return this.http.get("localhost:8080/foo");
}
I am using HttpClient
from import { HttpClient } from "@angular/common/http";
I also verified that the URL works in that service method by copy & pasting it into my browser. It does indeed, return JSON, which omits the possibility of a wrong URL or a typo.