我有一个简单的spring boot服务在调用数据库的docker端口8080上暴露的容器中运行mysql。
spring boot
docker
8080
mysql
当我击中localhost:8080/blogs我回来[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]
localhost:8080/blogs
[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]
当我直接在浏览器中点击它时,它的工作就很好。但是,当我从中尝试时,jQuery我得到了正常Access-Control-Allow-Origin。
jQuery
Access-Control-Allow-Origin
这是我的Spring Boot服务:
@SpringBootApplication @RestController public class ChrisboltonServiceApplication { public static void main(String[] args) { SpringApplication.run(ChrisboltonServiceApplication.class, args); } @Autowired private JdbcTemplate jdbcTemplate; @CrossOrigin @RequestMapping(path="/blogs") public @ResponseBody Iterable<ChrisBolton> getAllUsers() { List<ChrisBolton> result = jdbcTemplate.query( "SELECT * FROM blog", (rs, rowNum) -> new ChrisBolton(rs.getString("author"), rs.getString("title"), rs.getString("content"), rs.getDate("date")) ); return result; } }
这是我的jQuery:
$.ajax({ url: "http://localhost:8080/blogs", crossDomain: true }).done(function(data) { console.log(data); });
但我仍然收到此错误:
XMLHttpRequest cannot load http://localhost:8080/blogs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我曾尝试这种通过添加@CrossOrigin到getAllUsers()方法和我在类级别都试过了。我还查看了此内容,因为我在port上运行了UI 3000。但是那个联系不是特定于春天的。
@CrossOrigin
getAllUsers()
3000
编辑
添加我的请求标头:
GET /blogs HTTP/1.1 Host: localhost:8080 Connection: keep-alive Accept: */* Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36 Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8
网络标签(Chrome)中的响应:
因此,看来我正在“网络”标签中找回数据。但是,我console.log(data)生产Access-Control-Allow-Origin
console.log(data)
尝试将其添加到您的应用程序:
@SpringBootApplication @RestController public class ChrisboltonServiceApplication { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*"); } }; } ...
另外,请尝试crossDomain: true从中删除$.ajax()。
crossDomain: true
$.ajax()