Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handling of OPTIONS requests to address any potential CORS issues.
While my API effectively handles these OPTIONS requests, a challenge arises when the server responds to the OPTIONS request within client-side JavaScript. It seems to interpret this response as the actual response, thus disregarding the legitimate one. How can I prevent XHR from accepting the OPTIONS response?
Below is the code snippet for my function:
function makeRequest(method, url, data) {
document.body.style.cursor = "wait";
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status == 200) {
authToken = this.getResponseHeader('Authorization');
document.body.style.cursor = "initial";
console.log('responseText');
console.log(this.responseText);
resolve(JSON.parse(this.responseText));
} else if (this.status == 403) {
logout();
document.body.style.cursor = "initial";
reject({
status: this.status,
statusText: xhr.statusText
});
} else {
document.body.innerHTML = 'Error: ' + this.responseText;
document.body.style.cursor = "initial";
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
document.body.innerHTML = 'Error: ' + this.responseText;
document.body.style.cursor = "initial";
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", authToken);
xhr.send(data);
});
}
Although this approach functions correctly, it poses limitations as my application requires the ability to await responses from the function before proceeding with subsequent actions:
function retrieveCategories(active) {
document.body.style.cursor = "wait";
var data = JSON.stringify({ "active": active });
console.log(data);
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4 && this.status == 403) {
logout();
document.body.style.cursor = "initial";
} else if (this.readyState === 4 && this.status != 200) {
document.body.innerHTML = 'Error: ' + this.responseText;
document.body.style.cursor = "initial";
} else if (this.readyState === 4 && this.status == 200) {
authToken = this.getResponseHeader('Authorization');
categories = JSON.parse(this.responseText);
document.body.style.cursor = "initial";
}
});
xhr.open("POST", "http://127.0.0.1:7071/retrievecategories");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", authToken);
xhr.send(data);
}
Any suggestions or insights on how to overcome this issue would be greatly welcomed!