I’m attempting to retrieve information from the REST API of HP Alm. It works perfectly fine using a small curl script, allowing me to obtain my data. However, when I try to do the same using JavaScript alongside the fetch API and ES6 features, I encounter a significant obstacle. I’m receiving this error message:
Fetch API cannot load. The response for the preflight request did not pass access control validation: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://127.0.0.1:3000’ is hence denied access. The response had an HTTP status code of 501.
If an opaque response suffices, set the request’s mode to ‘no-cors’ to fetch the resource without CORS enabled.
I realize this issue arises because I am attempting to access the data from my localhost, and the appropriate method should be utilizing Cross-Origin Resource Sharing (CORS). Despite my efforts to implement this, it seems that my header configurations are either being ignored or that the problem lies elsewhere.
Is there an issue with my implementation? Am I going about this incorrectly? Unfortunately, I cannot check the server logs for more details. I’m quite perplexed by this situation.
function loginUser() {
const requestHeaders = new Headers();
requestHeaders.append('Content-Type', 'application/json');
requestHeaders.append('Accept', 'application/json');
requestHeaders.append('Access-Control-Allow-Origin', 'http://localhost:3000');
requestHeaders.append('Access-Control-Allow-Credentials', 'true');
requestHeaders.append('Authorization', 'Basic ' + btoa(username + ':' + password));
fetch(loginUrl, {
credentials: 'include',
method: 'POST',
headers: requestHeaders
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Login failed: ' + error.message));
}
I am using Chrome for this task. I also tried employing a Chrome CORS extension, but I encountered another error:
The value of the ‘Access-Control-Allow-Origin’ header in the response must not be a wildcard ‘*’ when the request credentials mode is ‘include’. Origin ‘http://127.0.0.1:3000’ is consequently not permitted access. The credentials mode for XMLHttpRequest initiated requests is managed by the withCredentials attribute.