I have a simple spring boot
service running in a docker
container exposed on port 8080
that is calling a mysql
database.
当我点击 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.
我已经通过将 @CrossOrigin
添加到 getAllUsers()
方法来尝试 这个,我已经在类级别尝试过。我也看过 这个,因为我在端口 3000
上运行我的 UI。但该链接不是特定于春季的。
编辑
添加我的请求标头:
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
原文由 Chris Bolton 发布,翻译遵循 CC BY-SA 4.0 许可协议
尝试将其添加到您的应用程序中:
另外,尝试从
crossDomain: true
中删除$.ajax()
。