我有一個簡單的服務,運行在端口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