网络服务
Kotori 提供了基于 axios 的 HTTP 客户端,但进行了更友好和符合 Kotori 设计理念的封装。Http
由 @kotori-bot/tools
库提供后经由 @kotori-bot/core
库传递给 kotori-bot
重新导出。
基础使用
HTTP 客户端可以通过上下文直接访问,或创建新实例:
tsx
// 使用上下文中的 http 实例
ctx.http.get('https://api.github.com/users/BIYUEHU').then((user) => {
console.log(user) // 直接访问响应数据
})
ctx.http.post('https://api.example.com/items', {
name: 'test',
value: 123
})
// 带查询参数的 get 请求
ctx.http.get('https://api.example.com/search', {
q: 'kotori',
page: 1
})
支持的请求方法:
get
: GET 请求post
: POST 请求put
: PUT 请求patch
: PATCH 请求delete
: DELETE 请求head
: HEAD 请求options
: OPTIONS 请求
自定义实例
你可以创建自定义的 HTTP 实例,并进行配置扩展:
tsx
// 创建自定义 HTTP 实例
const http = new Http({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
Authorization: 'Bearer token'
}
})
// 发送请求
http.get('/users')
http.post('/users', { name: 'kotori' })
// 扩展实例配置
const newHttp = http.extend({
headers: {
'X-Custom-Header': 'value'
}
})
newHttp.get('/users')
WebSocket 客户端和拦截器
除了基本的 HTTP 请求,还支持 WebSocket 连接和请求/响应拦截:
tsx
// WebSocket 支持
const ws = ctx.http.ws('wss://echo.websocket.org')
ws.onopen = () => {
ws.send('Hello WebSocket!')
}
ws.onmessage = (data) => {
console.log('Received:', data)
}
// 请求拦截器
ctx.http.request((config) => {
config.headers['X-Request-Time'] = Date.now()
return config
})
// 响应拦截器
ctx.http.response((response) => {
console.log(`Status: ${response.status}`)
return response
})
TIP
建议使用上下文中的 ctx.http
实例,除非需要特殊配置。