【发布时间】:2018-06-21 08:19:15
【问题描述】:
当我尝试访问我的 springboot restservice 时出现以下错误:
“加载http://localhost:8080/Lerneinheit 失败:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,源“http://localhost:8081”不存在允许访问。响应的 HTTP 状态代码为 403。"
我在 Google 上搜索了很多并将其添加到我的 RestController 类中:“@CrossOrigin(origins = "http://localhost:8081")"
@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/Lerneinheit")
public class LerneinheitController {
@Autowired
LerneinheitRepository lerneinheitRepository;
@RequestMapping(method=RequestMethod.GET)
public List<Lerneinheit> getAllLerneinheiten(){
List<Lerneinheit> lerneinheiten = new ArrayList<Lerneinheit>();
for(Lerneinheit l : lerneinheitRepository.findAll())
lerneinheiten.add(l);
return lerneinheiten;
}
这是我访问数据的 jQuery 代码:
var data = {}
data["query"] = $("#query").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080/Lerneinheit",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
服务器在端口 8080 上运行,我的客户端页面在端口 8081 上运行 "gulp-live-server": "0.0.31"。
我尝试了很多,如果有人可以帮助我,那就太棒了。
干杯, JohnRamb0r
【问题讨论】:
-
响应的 HTTP 状态码为 403——这就是你需要解决的问题。见en.wikipedia.org/wiki/HTTP_403。该 403 响应意味着您的服务器代码的其他部分禁止访问
/Lerneinheit路径。并且将@CrossOrigin添加到该Java 类将无法解决该问题。您需要在应用程序代码的那部分之前在服务器端的其他一些代码中修复它。您在该浏览器消息中看到提到Access-Control-Allow-Origin的唯一原因是因为您的服务器 - 像大多数服务器一样 - 没有将应用程序集标头添加到 4xx 响应。
标签: jquery spring-boot gulp cross-domain same-origin-policy