Ajax 通过'访问XMLHttpRequest;http://localhost:8092/URL' 来自原点';http://localhost:8080' 已被CORS策略阻止
我制作了一个SpringBootRESTAPI,将用户的nic、用户名和密码保存在mySQL数据库中。为此使用了tomcat 8096端口。然后我做了一个单独的项目来创建一个注册表单(JSP)来调用我之前创建的api。当我运行它并按下按钮时,我在控制台中得到了这个错误Ajax 通过'访问XMLHttpRequest;http://localhost:8092/URL' 来自原点';http://localhost:8080' 已被CORS策略阻止,ajax,spring-boot,rest,jsp,Ajax,Spring Boot,Rest,Jsp,我制作了一个SpringBootRESTAPI,将用户的nic、用户名和密码保存在mySQL数据库中。为此使用了tomcat 8096端口。然后我做了一个单独的项目来创建一个注册表单(JSP)来调用我之前创建的api。当我运行它并按下按钮时,我在控制台中得到了这个错误 Access to XMLHttpRequest at 'http://localhost:8092/api/leavecal/saveuser' from origin 'http://localhost:8080' has b
Access to XMLHttpRequest at 'http://localhost:8092/api/leavecal/saveuser' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我在JSP中使用的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1"/>
<title>Demo Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<center>
<div>
NIC No. : <input type="text" name="userNic" id="userNic"/>
</div>
Username : <input type="text" name="username" id="username"/>
<div>
Password : <input type="text" name="password" id="password"/>
</div>
<div>
<input type="submit" name="saveNewEmployee" id="saveNewEmployee" value="POST DATA" onclick="postDataFromAPI();"/>
</div>
</center>
<script>
function postDataFromAPI() {
var modelObj = {
userNic: $("#userNic").val(),
username: $("#username").val(),
password: $("#password").val()
};
console.log("post data:"+modelObj);
$.ajax({
type: "POST",
url: "http://localhost:8092/api/leavecal/saveuser",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify(modelObj),
success: function (data) {
console.log("POST API RESPONSE::"+data);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
</script>
</body>
</html>
演示应用程序
网卡号:
用户名:
密码:
函数postDataFromAPI(){
var modelObj={
userNic:$(“#userNic”).val(),
用户名:$(“#用户名”).val(),
密码:$(“#密码”).val()
};
console.log(“post数据:+modelObj”);
$.ajax({
类型:“POST”,
url:“http://localhost:8092/api/leavecal/saveuser",
标题:{
“内容类型”:“应用程序/json”
},
数据:JSON.stringify(modelObj),
成功:功能(数据){
log(“后API响应::”+数据);
},
错误:函数(jqXHR、textStatus、errorshown){
}
});
}
感谢您的帮助使用
@CrossOrigin
控制器类顶部的注释