ChatGPT API 接入指南:如何使用 JavaScript 发出 HTTP 请求
使用 JavaScript 发出 HTTP 请求以接入 ChatGPT API
要使用 JavaScript 发出 HTTP 请求以接入 ChatGPT API,可以使用浏览器内置的 XMLHttpRequest 对象或使用现代的 fetch API。下面是使用这两种方法发出 HTTP 请求的示例代码:
使用 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://lytcreate.com/api/chat/", true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = {
token: "个人中心获取的token",
question: "user:请求的问题"
};
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send(JSON.stringify(data));
使用 fetch API
var url = "https://lytcreate.com/api/chat/";
var data = {
token: "个人中心获取的token",
question: "user:请求的问题"
};
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
注意:
- 上述代码中的 URL、token 和问题是示例数据,你需要替换为你实际使用的值。
- 根据你的需求,你可能还需要对请求进行其他配置,比如添加请求头、处理响应等。
希望以上内容对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/bb4G 著作权归作者所有。请勿转载和采集!