my JS and HTML is at below, when I enter this URL: http://localhost:8080/api/languages/getall
in Chrome, it returns [{"id":1,"name":"c"},{"id":2,"name":"java"}],
but the code at below is not working, it might be the root caused and how to fix it?
$.ajax({
url: "http://localhost:8080/api/languages/getall",
type: 'GET',
dataType: 'json', // json?
CORS: true ,
contentType:'application/json',
headers: {
'Access-Control-Allow-Origin': '*',
},
success: function (data){
console.log(data);
}
});
html
<!DOCTYPE html>
<html>
<head>
<title>How to consume RESTful Web Service using jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/consume-rest.js"></script>
</head>
<body>
<div>
<h3>How to consume RESTful Web Service using jQuery</h3>
<p id="id">ID: </p>
<p id="content">Content: </p>
</div>
</body>
</html>
spring
@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/languages/getall")
List<GetLanguageResponse>getAllResponse(){
return languagesService.getAllResponse();
}//it returns array of object
https://pasteboard.co/KZ7BZqMSh7yX.png the link shows the answer of backend server it works.And i also added cross origin above the code .Error is still same,"from origin 'null' has been blocked by CORS policy" and "jquery.min.js:2 GET http://localhost:8080/api/languages/getall net::ERR_FAILED"
Just to let yall know in my react code it works
const App = () => {
const [groups, setGroups] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
fetch('api/languages/getall')
.then(response => response.json())
.then(data => {
setGroups(data);
setLoading(false);
})
}, []);
if (loading) {
return <p>Loading...</p>;
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<div className="App-intro">
<h2>JUG List</h2>
{groups.map(group =>
<div key={group.id}>
{group.name}
</div>
)}
</div>
</header>
</div>
);
}