我正在運行錯誤「No'Access-Control-Allow-Origin'標題出現在請求的資源上」when我試圖通過Chrome在我的機器上運行.html文件。它試圖訪問我在localhost:8080上運行的SpringBoot Web服務。SpringBoot和Html:沒有'Access-Control-Allow-Origin'標題出現在請求的資源上
我能夠通過直接通過Chrome調用Web服務本身來獲得結果,但試圖通過index.html調用Web服務給我提供了訪問控制錯誤。
我也嘗試了春季tutorial,但我仍然遇到相同的問題。
的index.html
<title>My Worst Enemy</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function()
{
$("#run").click(function()
{
var summonerName = document.getElementById("summonerName");
console.log(summonerName.value);
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost:8080/summonerName/" + summonerName.value,
success: function(data){
alert(data);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="summonerName" id="summonerName" value="Zann Starfire">
<button id="run">Run Summoner</button><br>
</body>
</html>
WebController.java
package com.myWorstEnemy.web.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class WebController
{
@RequestMapping("/")
public String helloWorld()
{
return "Hello world!";
}
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(method = RequestMethod.GET, value = "/summonerName/{summonerName}")
public String summonerName(@PathVariable String summonerName)
{
return "The summoner name = " + summonerName;
}
}
爲什麼這是一個跨域請求?我從我的電腦運行index.html,我不認爲localhost與我運行的網頁不同,但我顯然缺少一些東西。
有什麼我可以添加到我的index.html來啓用交叉來源請求,還是我需要在別處做?
您是通過Web應用程序還是通過文件系統獲取文件? Chrome中的url是http://localhost/.../index.html還是file://.../index.html? file://我認爲是一個不同的域名;嘗試起源='*' – okaram
*來源*這個詞並不意味着「相同的系統」或「相同的環境」。 *來源*這個詞有非常具體的技術含義;它意味着方案+主機+端口的組合。請參閱https://tools.ietf.org/html/rfc6454#section-5。出於同源策略的目的,只有當它們的方案+主機+端口的組合完全匹配時,兩個源才匹配。 https://en.wikipedia.org/wiki/Same-origin_policy因此,根據這些規則的來源是什麼,你正在嘗試的是一個跨域請求 – sideshowbarker
我真的沒有考慮file:// being不同的起源,但這是有道理的。我只是沒有注意到我是如何運行網頁的。謝謝您的幫助! – Styrfire