使用ts封装一个ajax请求
时间: 2024-05-15 10:18:53 浏览: 185
好的,使用ts封装一个ajax请求可以分为以下几个步骤:
1. 定义一个接口RequestOptions,用于传递请求参数。
```typescript
interface RequestOptions {
url: string;
method: string;
data?: any;
headers?: { [key: string]: any };
}
```
2. 定义一个函数request,用于发送请求。
```typescript
async function request(options: RequestOptions) {
const response = await fetch(options.url, {
method: options.method,
body: JSON.stringify(options.data),
headers: Object.assign({}, options.headers, {
'Content-Type': 'application/json',
}),
});
return response.json();
}
```
3. 调用request函数,发送请求并处理响应。
```typescript
request({
url: '/api/user/login',
method: 'POST',
data: { username: 'admin', password: 'admin123' },
}).then((response) => {
console.log(response);
});
```
以上是使用ts封装一个ajax请求的基本步骤。如果有需要,还可以根据实际情况对接口RequestOptions和函数request进行扩展。
阅读全文
相关推荐


















