Reputation: 438
I made a Spring Boot Rest api to save users nic, username and password in a mySQL database. Used the tomcat 8096 port for that. Then I made a seperate project to make a registration form (JSP) to call the api I made earlier. When I run it and press the button, I got this error in the console ;
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.
This is the code I used in my 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>
Any help is appreciated
Upvotes: 0
Views: 847
Reputation: 1023
Use
@CrossOrigin
annotation on top of your controller class.
Upvotes: 1