【一】基本使用
npm install axios -S
// 13 axios使用
import axios from "axios";
// 相当于写在了created中--》页面加载完,就发送请求
axios.get('自己地址').then(res => {
console.log(res)
})
【二】小电影案例
【1】普通使用
<script setup>
import {reactive} from "vue";
import axios from "axios";
// 初始化一个空的响应式对象,你可以往这个对象中添加属性和值
const filmList = reactive({})
axios.get('http://127.0.0.1:8000/api/v1/films/').then(res => {
console.log(res.data)
if(res.data.code==100){
// 加载成功了-->把返回的数据,放到变量中
filmList.result=res.data.result // 能赋值,但是不是响应式
console.log('---',filmList)
}else{
alert(res.data.msg)
}
})
</script>
<template>
<h1>显示电影案例</h1>
<div v-for="item in filmList.result">
<h3>{{ item.name }}</h3>
<img :src="item.poster" alt="" height="300px" width="250px">
</div>
</template>
【2】高级使用
- 使用解构赋值
- Object.assign() 将从API获取的数据(res.data.result 或其他形式的数据)合并到现有的 filmList.result 对象中
const filmList = reactive({})
axios.get('http://127.0.0.1:8000/api/v1/films/').then(res => {
console.log(res.data)
if (res.data.code == 100) {
//2.1 直接把res.data.result 复制到filmList.result
Object.assign(filmList.result,res.data.result)
// 2.2 解构赋值
let {data}=res // res={data:{code:100,msg:成功}}
Object.assign(filmList.result,data.result)
//2.3 解构赋值
let {data: {result}} = res
Object.assign(filmList.result, result)
// 2.4 解构赋值
//let {data} = res // {code:100,msg:成功,result:[]}
//直接把data给res,result空的就会覆盖成新的
Object.assign(filmList, data)
} else {
alert(res.data.msg)
}
})
【三】async await
- console.log('1111')打印出来再执行console.log(data)
- 调用一个异步函数时,它会立即返回一个Promise,而不会阻塞后续代码的执行
async function load() {
// response--》就是原来then中的res
// let response= await axios.get('http://127.0.0.1:8000/api/v1/films/')
// data --》就是原来then中的res.data
// 正常返回的then的给了 response--》原来catch的会被异常捕获
try {
let {data} = await axios.get('http://127.0.0.1:8000/api/v1/films/')
console.log(data)
Object.assign(filmList, data)
} catch (err) {
alert('请求失败')
}
load()
console.log('1111')
【四】 axios 其它配置项
//axios.get()
//axios.post()
axios({
url:'地址',
method:'post',
headers: {'token': 'adsfa.adsfa.adsf',contentType:'application/json'},
params: {name: lqz,age:19},
data: {firstName: 'Fred'},
timeout: 1000,
})
// 更多参数
{
//1 `url` 是用于请求的服务器 URL
url: '/user',
//2 `method` 是创建请求时使用的方法
method: 'get', // 默认值
//3 `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
//4 `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理
return data;
}],
//5 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
//6 params` 是与请求一起发送的 URL 参数
// 必须是一个简单对象或 URLSearchParams 对象
params: {
ID: 12345
},
// 7 aramsSerializer`是可选方法,主要用于序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
//8 data` 是作为请求体被发送的数据
// 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
// 在没有设置 `transformRequest` 时,则必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属: FormData, File, Blob
// - Node 专属: Stream, Buffer
data: {
firstName: 'Fred'
},
// 发送请求体数据的可选语法
// 请求方式 post
// 只有 value 会被发送,key 则不会
data: 'Country=Brasil&City=Belo Horizonte',
// 0imeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)
// 11 thCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
//12 dapter` 允许自定义处理请求,这使测试更加容易。
// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},
//13 auth` HTTP Basic Auth
auth: {
username: 'lqz'
password: '123‘
},
//14 `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值
//15 `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默认值
//16 `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值
//17 `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
//18 `onUploadProgress` 允许为上传处理进度事件
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
//19 `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},
// 20 `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,
//21 `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,
// 22 `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},
// 23 `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值
//24 `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // default
//25 `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
//26 `proxy` 定义了代理服务器的主机名,端口和协议。
// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
// 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
// `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
// 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
// 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'lqz',
password: '123'
}
},
// 27 see https://axios-http.com/zh/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),
// 28 `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // 默认值
}
【五】axios请求和响应拦截器
- 如果想在axios发送请求之前,或者是数据响应回来在执行then方法之前做一些额外的工作,可以通过拦截器完成
// 添加请求拦截器 请求发送之前
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器 数据响应回来
axios.interceptors.response.use(
function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
},
function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
}
);
import axios from 'axios'
// 创建instance实例
const instance = axios.create({
baseURL:'https://api.lqz.com',
timeout:10000
})
// 添加请求拦截
instance.interceptors.request.use(
// 设置请求头配置信息
config=>{
//处理指定的请求头
console.log("before request")
config.headers.Accept = 'application/json, text/plain, text/html,*/*'
return config
},
// 设置请求错误处理函数
error=>{
console.log("request error")
return Promise.reject(error)
}
)
// 添加响应拦截器
instance.interceptors.response.use(
// 设置响应正确时的处理函数
response=>{
console.log("after success response")
console.log(response)
return response
},
// 设置响应异常时的处理函数
error=>{
console.log("after fail response")
console.log(error)
return Promise.reject(error)
}
)
// 默认导出
export default instance