使用class封装一个http请求
时间: 2024-04-02 07:34:23 浏览: 15
好的,下面是一个使用class封装http请求的例子:
```
class HttpRequest {
constructor() {
this.baseUrl = 'https://api.example.com';
}
async get(endpoint) {
const response = await fetch(`${this.baseUrl}${endpoint}`);
const data = await response.json();
return data;
}
async post(endpoint, body) {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
return data;
}
}
const httpRequest = new HttpRequest();
async function fetchData() {
const data = await httpRequest.get('/users');
console.log(data);
}
fetchData();
```
在这个例子中,我们创建了一个名为HttpRequest的类,它有一个构造函数和两个实例方法:get和post。构造函数用于初始化baseUrl属性,get方法用于发送GET请求,post方法用于发送POST请求。
我们使用fetch函数发送了http请求,并使用async/await语法等待响应结果。在get和post方法中,我们使用模板字符串拼接出请求的完整URL,并将请求体转换为JSON格式。在post方法中,我们还设置了请求头Content-Type为application/json。
最后,我们创建了一个HttpRequest的实例,并使用它的get方法发送了一个GET请求,输出了响应结果。