我正在运行错误“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