功能特点:
- 在浏览器中发送XMLHttpRequests请求
- 在node.js中发送http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 等
axios请求方式
- axios(config)------------->config指配置
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.get(url[, data[, config]])
- axios.post(url[, data[, config]])
- axios.patch(url[, data[, config]])
当需要同时发送两个请求时:
- 使用 axios.all, 可以放入多个请求数组
- axios.all([])返回的结果是一个数组,使用axios.spread 可将数组[res1, res2]展开为 res1, res2
常见的配置选项(只列出了最常用的)
- 请求地址: url:'user',
- 请求类型: method: 'get'
- 基本路径: baseURL: 'http://www.mt.com/api'
- 自定义请求头: headers:{'x-Request-With':'XMLHttpRequest'}
- 请求体: data: {key: 'aa'}
- 超时设置: timeout:1000
拦截器:(请求拦截&发送拦截)
创建项目
命令:
- vue create 项目名
- pnpm install
- pnpm install axios ---安装axios才可以使用
在App.js文件中
import CSRequest from './service'//引入封装的axios
CSRequest.request({
url: "http://xxxx/xxxx?id=500xxx346",
}).then(res => {
console.log("res", res)
})
CSRequest.get( {
url: "/xxxxx",
params: {
id:500xxx346
}
}).then(res => {
console.log("res", res)
})
新建一个service文件 下的index.js中
import axios from 'axios'
// class CSRequest {
// request(config) {
// return axios.request(config)
// }
// }---->最基础的封装
//用promise做封装
class CSRequest {
constructor(baseURL, timeout=10000) {
this.instance = axios.create({//方便传默认参数 用实例来代替
baseURL,
timeout
})
}
request(config) {
return new Promise((resolve, reject)=>{
this.instance.request(config).then((res, err) => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}
get(config) {
return this.request( { ...config, method: "get" })//解构参数
}
post(config) {
return this.config({ ...config, method: "post" })
}
}
export default new CSRequest("http://123.xxxx:xxxx")//这样就有了基本的URL 后续相对路径就不用写相同的部分了