I have created a secure Rest API in Spring boot which I want to send a POST fetch request to using java script. I have defined an InMemoryUser in my configuration class. The problem is that, everything works perfectly fine when I send a POST request using Postman. But when i send a POST request using Java script i get error.
This is how i tried to send the post request using the Java Script
document.querySelector(.btn_save_student
)
.addEventListener(‘click’, async()=> {
let name = document.getElementById(name
).value;
let email = document.getElementById(email
).value;
let user_password = document.getElementById(user_password
).value;
let username = 'user';
let password = '12345';
let auth = btoa(`${username}:${password}`);
try {
let response = await fetch(`http://localhost:8081/api/v1/employee/save`, {
method: 'POST',
headers: {
'Authorization': `Basic ${auth}`,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify ({
'name':name,
'email': email,
'password': user_password
})
})
let data_res = await response.json();
console.log(data_res);
} catch (error) {
alert(error)
}
});
And I got this error:
Access to fetch at ‘http://localhost:8081/api/v1/employee/save’ from origin ‘http://127.0.0.1:5500’ 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. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.