We are using Azure bot framework in node js and using Language studio Question answer Rest API service. The api calls returns 401 when requested from the code but works just fine from postman calls. The botframework is deployed on Azure web app service.
let options = {
method: 'post',
url: `${process.env.LanguageEndpointHostName}language/:query-text?api-version=2021-10-01`,
headers: {
'Ocp-Apim-Subscription-Key': process.env.LanguageEndpointKey,
'Content-Type': 'application/json'
},
data: inputData
};
let result = await axios(options);
Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.
I used the correct API URL and header with subscription key. It works perfect from postman but not from the JavaScript node js app Axios call. All other API calls of azure language studio service works fine. Please advise
Initially, In my environment, I got the same error when I tried with JavaScript.
Error:
The above error 401 error indicates that the request was not authorized. This could be due to an invalid subscription key or an incorrect API endpoint.
In my environment, when I used the old key I got the same error. After rotating the keys, it worked successfully.
Code:
const axios = require('axios');
const subscriptionKey = 'xxxxx'; // newkey
const endpoint = 'xxxxxxxx';
const url = `https://${endpoint}/text/analytics/v3.0/languages`;
const inputData = {
documents: [
{
id: '1',
text: 'Power and charging. It takes two to four hours to fully charge the Surface Pro 4 battery from an empty state. It can take longer if you’re using your Surface for power-intensive activities like gaming or video streaming while you’re charging it.'
},
{
id: '2',
text: 'You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.'
}
]
};
const options = {
method: 'post',
url,
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-Type': 'application/json'
},
data: inputData
};
axios(options)
.then(response => {
const documents = response.data.documents;
documents.forEach(document => {
console.log(`Document ${document.id} is in ${document.detectedLanguage.name}`);
});
})
.catch(error => {
console.error(error.response.data);
});
Output:
Document 1 is in English
Document 2 is in English
Reference:
Rotate keys in Azure AI services - Azure AI services | Microsoft Learn