使用 TypeScript 重构 axios
- 在浏览器端使用 XMLHttpRequest 对象通讯
- 支持 Promise API
- 支持请求和响应的拦截器
- 支持请求数据和响应数据的转换
- 支持请求的取消
- JSON 数据的自动转换
- 客户端防止 XSS
const axios = require('axios')
axios({
url: '/extend/post',
method: 'post',
data: {
msg: 'hi'
}
})
axios.request({
url: '/extend/post',
method: 'post',
data: {
msg: 'hello'
}
})
axios.get('/extend/get')
axios.options('/extend/options')
axios.delete('/extend/delete')
axios.head('/extend/head')
axios.post('/extend/post', { msg: 'myPost' })
axios.put('/extend/put', { msg: 'myPut' })
axios.patch('/extend/patch', { msg: 'myPatch' })
const axios = require('axios')
axios.interceptors.request.use(config => {
config.headers.test += '1'
return config
})
axios.interceptors.request.use(config => {
config.headers.test += '2'
return config
})
axios.interceptors.request.use(config => {
config.headers.test += '3'
return config
})
axios.interceptors.response.use(res => {
res.data += '1'
return res
})
let interceptor = axios.interceptors.response.use(res => {
res.data += '2'
return res
})
axios.interceptors.response.use(res => {
res.data += '3'
return res
})
axios.interceptors.response.eject(interceptor)
axios({
url: '/interceptor/get',
method: 'get',
headers: {
test: ''
}
}).then(res => {
console.log(res.data)
})
import axios, { Canceler } from 'axios'
const CancelToken = axios.CancelToken
const source = CancelToken.source()
axios
.get('/cancel/get', {
cancelToken: source.token
})
.catch(function(e) {
if (axios.isCancel(e)) {
console.log('Request canceled', e.message)
}
})
setTimeout(() => {
source.cancel('Operation canceled by the user.')
axios.post('/cancel/post', { a: 1 }, { cancelToken: source.token }).catch(function(e) {
if (axios.isCancel(e)) {
console.log(e.message)
}
})
}, 100)
let cancel: Canceler
axios
.get('/cancel/get', {
cancelToken: new CancelToken(c => {
cancel = c
})
})
.catch(function(e) {
if (axios.isCancel(e)) {
console.log('Request canceled')
}
})
setTimeout(() => {
cancel()
}, 200)
router.get('/cancel/get', function (req, res) {
setTimeout(() => {
res.json('hello')
}, 1000)
})
router.post('/cancel/post', function (req, res) {
setTimeout(() => {
res.json(req.body)
}, 1000)
})
const instance = axios.create()
function calculatePercentage(loaded: number, total: number) {
return Math.floor(loaded * 1.0) / total
}
function loadProgressBar() {
const setupStartProgress = () => {
instance.interceptors.request.use(config => {
NProgress.start()
return config
})
}
const setupUpdateProgress = () => {
const update = (e: ProgressEvent) => {
console.log(e)
NProgress.set(calculatePercentage(e.loaded, e.total))
}
instance.defaults.onDownloadProgress = update
instance.defaults.onUploadProgress = update
}
const setupStopProgress = () => {
instance.interceptors.response.use(
response => {
NProgress.done()
return response
},
error => {
NProgress.done()
return Promise.reject(error)
}
)
}
setupStartProgress()
setupUpdateProgress()
setupStopProgress()
}
loadProgressBar()
const downloadEl = document.getElementById('download')
downloadEl!.addEventListener('click', e => {
instance.get('图片URL')
})
const uploadEl = document.getElementById('upload')
uploadEl!.addEventListener('click', e => {
const data = new FormData()
const fileEl = document.getElementById('file') as HTMLInputElement
if (fileEl.files) {
data.append('file', fileEl.files[0])
instance.post('/more/upload', data)
}
})