一、服务端和axios请求之间传参
data—body
- axios请求使用
data
携带参数,服务端使用req.body
接收
axios({
method: 'POST',
url: 'http://127.0.0.1:8001/api/addUser',
data: {
id: 18,
username: 'admin18',
password: '000000',
nickname: 'admin999',
email: '333@qq.com',
user_ic: ''
}
}).then((response) => {
console.log(response)
})
- data的数据格式为一个对象时,在服务端要使用内置中间件将其转化成
json
格式数据,否则传递过来的数据为空对象
app.use(express.json())
:arg
—params
- axios请求中在url地址中使用
:arg
形式传递一个参数时,在服务端要使用params
接收一个对象
二、axios发起请求
get
axios({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
console.log(response)
})
post
axios({
method: 'POST',
url: 'http://127.0.0.1:8001/api/addUser',
data: {
id: 33,
username: 'admin33',
password: '000000',
nickname: 'admin999',
email: '333@qq.com',
user_ic: ''
}
}).then((response) => {
console.log(response)
})
put
axios({
method: 'PUT',
url: 'http://127.0.0.1:8001/api/updateUser/33',
data: {
username: '你好好笑',
nickname: '我不好笑'
}
}).then((response) => {
console.log(response)
})
delete
axios({
method: 'delete',
url: 'http://127.0.0.1:8001/api/deleteUser/33'
}).then((response) => {
console.log(response)
})
axios.request()
axios
.request({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/34'
})
.then((response) => {
console.log(response)
})
axios.post()
axios
.post('http://127.0.0.1:8001/api/addUser', {
id: 34,
username: 'admin34',
password: '000000',
nickname: 'admin999',
email: '333@qq.com',
user_ic: ''
})
.then((response) => {
console.log(response)
})
三、默认配置
const btns = document.querySelectorAll('button')
axios.defaults.method = 'GET'
axios.defaults.baseURL = 'http://127.0.0.1:8001'
axios.defaults.timeout = 10
btns[0].onclick = function () {
axios({
url: '/api/user/33'
}).then((response) => {
console.log(response)
})
}
四、创建axios实例发起请求
const duanzi = axios.create({
baseURL: 'http://127.0.0.1:8001',
timeout: 2000
})
duanzi.get('/api/user/33').then((response) => {
console.log(response.data)
})
五、拦截器
- 本质上就是一个函数
- 请求拦截器:发送请求之前可以通过回调函数,检测请求的内容和参数,如果请求有问题,就可以通过请求拦截器中止请求
- 响应拦截器:对请求失败或成功的结果进行处理
请求拦截器
axios.interceptors.request.use(
function (config) {
console.log('请求拦截器 成功 - 1号')
config.params = { a: 100 }
return config
},
function (error) {
console.log('请求拦截器 失败 - 1号')
return Promise.reject(error)
}
)
响应拦截器
axios.interceptors.response.use(
function (response) {
console.log('响应拦截器 成功 1号')
return response.data
},
function (error) {
console.log('响应拦截器 失败 1号')
return Promise.reject(error)
}
)
六、取消请求
const btns = document.querySelectorAll('button')
let cancel = null
btns[0].onclick = function () {
if (cancel !== null) {
cancel()
}
axios({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/33',
cancelToken: new axios.CancelToken(function (c) {
cancel = c
})
}).then((response) => {
console.log(response)
cancel = null
})
}
btns[1].onclick = function () {
cancel()
}
七、axios对象的简单实现
function Axios(config) {
this.defaults = config
this.intercepters = {
request: {},
response: {}
}
}
Axios.prototype.request = function (config) {
console.log('发送 AJAX 请求 请求的类型为 ' + config.method)
}
Axios.prototype.get = function (config) {
return this.request({ method: 'GET' })
}
Axios.prototype.post = function (config) {
return this.request({ method: 'POST' })
}
function createInstance(config) {
let context = new Axios(config)
let instance = Axios.prototype.request.bind(context)
Object.keys(Axios.prototype).forEach((key) => {
instance[key] = Axios.prototype[key].bind(context)
})
Object.keys(context).forEach((key) => {
instance[key] = context[key]
})
return instance
}
let axios = createInstance()
axios.get({})
axios.post({})
八、axios请求发送简单实现
function Axios(config) {
this.config = config
}
Axios.prototype.request = function (config) {
let promise = Promise.resolve(config)
let chains = [dispatchRequest, undefined]
let result = promise.then(chains[0], chains[1])
return result
}
function dispatchRequest(config) {
return xhrAdapter(config).then(
(response) => {
return response
},
(error) => {
throw error
}
)
}
function xhrAdapter(config) {
console.log('xhrAdapter 函数执行')
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(config.method, config.url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
config: config,
data: xhr.response,
headers: xhr.getAllResponseHeaders(),
request: xhr,
status: xhr.status,
statusText: xhr.statusText
})
} else {
reject(new Error('请求失败 失败的状态码为' + xhr.status))
}
}
}
})
}
let axios = Axios.prototype.request.bind(null)
axios({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
console.log(response)
})
九、拦截器简单实现和使用
function Axios(config) {
this.config = config
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
}
}
Axios.prototype.request = function (config) {
let promise = Promise.resolve(config)
const chains = [dispatchRequest, undefined]
this.interceptors.request.handlers.forEach((item) => {
chains.unshift(item.fulfilled, item.rejected)
})
this.interceptors.response.handlers.forEach((item) => {
chains.push(item.fulfilled, item.rejected)
})
while (chains.length > 0) {
promise = promise.then(chains.shift(), chains.shift())
}
return promise
}
function dispatchRequest(config) {
return new Promise((resolve, reject) => {
resolve({
status: 200,
statusText: 'OK'
})
})
}
let context = new Axios({})
let axios = Axios.prototype.request.bind(context)
Object.keys(context).forEach((key) => {
axios[key] = context[key]
})
function InterceptorManager() {
this.handlers = []
}
InterceptorManager.prototype.use = function (fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected
})
}
axios.interceptors.request.use(
function one(config) {
console.log('请求拦截器 成功 - 1号')
return config
},
function one(error) {
console.log('请求拦截器 失败 - 1号')
return Promise.reject(error)
}
)
axios.interceptors.request.use(
function two(config) {
console.log('请求拦截器 成功 - 2号')
return config
},
function two(error) {
console.log('请求拦截器 失败 - 2号')
return Promise.reject(error)
}
)
axios.interceptors.response.use(
function (response) {
console.log('响应拦截器 成功 1号')
return response
},
function (error) {
console.log('响应拦截器 失败 1号')
return Promise.reject(error)
}
)
axios.interceptors.response.use(
function (response) {
console.log('响应拦截器 成功 2号')
return response
},
function (error) {
console.log('响应拦截器 失败 2号')
return Promise.reject(error)
}
)
axios({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/33'
}).then((response) => {
console.log(response)
})
十、取消请求的简单实现
function Axios(config) {
this.config = config
}
Axios.prototype.request = function (config) {
return dispatchRequest(config)
}
function dispatchRequest(config) {
return xhrAdapter(config)
}
function xhrAdapter(config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(config.method, config.url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300
resolve({
status: xhr.status,
statusText: xhr.statusText
})
} else {
reject(new Error('请求失败'))
}
}
}
if (config.cancelToken) {
config.cancelToken.promise.then((value) =>
xhr.abort()
reject(new Error('请求已经被取消'))
})
}
})
}
const context = new Axios({})
const axios = Axios.prototype.request.bind(contex
function CancelToken(executor) {
var resolvePromise
this.promise = new Promise((resolve) => {
resolvePromise = resolve
})
executor(function () {
resolvePromise()
})
}
const btns = document.querySelectorAll('button')
let cancel = null
btns[0].onclick = function () {
if (cancel !== null) {
cancel()
}
let cancelToken = new CancelToken(function (c)
cancel = c
})
axios({
method: 'GET',
url: 'http://127.0.0.1:8001/api/user/33',
cancelToken: cancelToken
}).then((response) => {
console.log(response)
cancel = null
})
}
btns[1].onclick = function () {
cancel()
}