I’m trying to create an app that uses a REST API from Microsoft Azure to get information from a user’s Azure portal and display them on my Nextcloud app. When the app page loads, it makes two GET requests to Microsoft. However, while the first request goes through, the second one doesn’t. Instead, I get a 401 error stating that Authentication failed and that the Authorization header is missing, despite it using the same header as the first request.
Here’s the JavaScript that makes the API calls:
let sendRequest = (ev) => {
let subscriptionURL = 'https://management.azure.com/subscriptions?api-version=2022-12-01';
let token = sessionStorage.getItem('MyToken');
let header = new Headers();
header.append('Authorization', `Bearer ${token}`);
let request = new Request(subscriptionURL, {
method: 'GET',
mode: 'cors',
headers: header
});
function fetchSubscriptionID() {
let subID;
fetch(request)
.then(response => response.json())
.then(data => {
console.log(data);
subID = data.value[0].id;
})
.catch(error => {
console.error(error.message);
});
return new Promise((resolve) => {
setTimeout(() => {
resolve(subID);
}, 2000);
})
}
async function fetchVM() {
const subscriptionID = await fetchSubscriptionID();
sessionStorage.setItem('subID', subscriptionID);
let VMInfo;
let vmURL = 'https://management.azure.com'.concat(subscriptionID, '/providers/Microsoft.Compute/virtualMachines?api-version=2023-07-01');
let vmRequest = new Request(vmURL, {
method: 'GET',
mode: 'cors',
headers: header
});
console.log(vmRequest);
fetch(vmRequest)
.then(response => response.json())
.then(data => {
console.log(data);
VMInfo = data;
})
.catch(error => {
console.log("Error message:")
console.error(error.message);
});
return new Promise((resolve) => {
setTimeout(() => {
resolve(VMInfo);
}, 2000);
})
}
}
It’s not an issue with the API, as I’m able to get the JavaScript to work fine on local API files, they just don’t work on my Nextcloud dev environment. I’ve also tried changing in what order I put the calls in to see if it was an issue with the specific request I’m making. However, any request is able to go through just fine if it’s the first call and all subsequent calls don’t work.
In case it will be useful in helping me, here’s the documentation of the API endpoints I am using: