我有一个简单的服务,运行在端口8080
上的docker
容器中,该端口调用mysql
数据库。'Access-Control-Allow-Origin'with spring boot
当我打localhost:8080/blogs
,我回来[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]
这工作得很好,当我直接在浏览器打它。但是,当我从jQuery
尝试它时,我得到正常的Access-Control-Allow-Origin
。
这里是我的春天启动服务:
@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.
我已经试过this将@CrossOrigin
添加到getAllUsers()
方法我已经在课堂上尝试过了。我也看过this,因为我正在运行我的端口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):
[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]
所以看起来我得到的数据回到网络标签。然而,我console.log(data)
产生Access-Control-Allow-Origin
我仍然保留'@ CrossOrigin'吗?仍然有相同的错误。 –
另外,我在上面添加了使用docker并暴露端口8080的事实。也许这可能是问题的一部分? –
其实,所有的东西都应该一直和'@ CrossOrigin'一起工作。我刚刚在这里测试,它工作正常。您使用码头集装箱的事实应该会影响它。你的容器基于什么形象?在容器内部的弹簧靴前没有某种代理吗? – acdcjunior