以下程序在在HBuilder中调试时是正常的,能够正常调用讯飞星火的API,实现输出。
然而,在正常的浏览器中运行时,输出永远是“No response from API”,主要是在send之后,xhr.status永远是0,不知道是什么原因???
function callXinghuoAPI() {
var userInput = document.getElementById('userInput').value;
var apiKey = '**************************'; // 替换为你的API密钥
var apiPassword = '********************************************';
var apiurl = 'https://spark-api-open.xf-yun.com/v1/chat/completions';
var userID = '**********';
if (!userInput) {
document.getElementById('apiResponse').innerText = 'Please enter some input';
return;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', apiurl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer ' + apiPassword);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
alert(xhr.status) //在HBuilder中调试时是正常的200,但是在正常的浏览器中运行时,这里永远是0
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
if (data && data.choices && data.choices.length > 0) {
document.getElementById('apiResponse').innerText = 'API Response: ' + data.choices[0].message.content;
} else {
document.getElementById('apiResponse').innerText = 'No response from API';
}
} else {
console.error('Error:', xhr.statusText);
document.getElementById('apiResponse').innerText = 'Error calling API';
}
}
};
var requestBody = JSON.stringify({
'model': 'generalv3.5',
'user': userID,
'messages': [{'role': 'user','content': userInput}]
});
alert(requestBody)
xhr.send(requestBody);
}
0 个回复