您的位置:首页 >> Vue >> 《和小米一起学Vue.js》— axios

《和小米一起学Vue.js》— axios

[ 孤狼 | 2023-01-09 13:15:41 | Vue | 1651°C | 0条评论 ]

Axios 是一个基于 promise 网络请求库,作用于 node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js  http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。在vue中,一般用来发送请求的都是axios。


安装

直接使用npm的方式安装即可(这里我也以这种方式)

npm install axios --save

单页面使用也可以直接使用cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


引入到vue

使用npm安装完 axios 之后,新建一个项目。要使用axios,只需要在当前文件引用一下即可直接使用。

TIP:由于axios默认支持promise,所以可以直接把返回结果当promise对象使用。所以可以直接使用then()和catch()

TIP:由于axios默认不支持跨域,所以你需要访问一个允许跨域的接口或者是Google一下,或者是配置一个代理服务器


axios 请求方法

通用方法:

axios(config) axios(url[, config])

为了方便起见,已经为所有支持的请求方法提供了别名。

axios.request(config) 

axios.get(url[, config]) 

axios.delete(url[, config]) 

axios.head(url[, config]) 

axios.options(url[, config]) 

axios.post(url[, data[, config]]) 

axios.put(url[, data[, config]]) 

axios.patch(url[, data[, config]])


请求配置

如果想要发送请求,就要先了解一下请求的配置,这样我们才能知道到底能发送那些请求。下面就是官网罗列出来的config请求配置项目。

{
// `url` 是用于请求的服务器 URL
url: '/user',

// `method` 是创建请求时使用的方法
method: 'get', // 默认值

// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',

// `transformRequest` 允许在向服务器发送前,修改请求数据
// 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
// 你可以修改请求头。
transformRequest: [function (data, headers) {
// 对发送的 data 进行任意转换处理

return data;
}],

// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对接收的 data 进行任意转换处理

return data;
}],

// 自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},

// `params` 是与请求一起发送的 URL 参数
// 必须是一个简单对象或 URLSearchParams 对象
params: {
ID: 12345
},

// `paramsSerializer`是可选方法,主要用于序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},

// `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',

// `timeout` 指定请求超时的毫秒数。
// 如果请求时间超过 `timeout` 的值,则请求会被中断
timeout: 1000, // 默认值是 `0` (永不超时)

// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default

// `adapter` 允许自定义处理请求,这使测试更加容易。
// 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
adapter: function (config) {
/* ... */
},

// `auth` HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},

// `responseType` 表示浏览器将要响应的数据类型
// 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 浏览器专属:'blob'
responseType: 'json', // 默认值

// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
// 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默认值

// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
xsrfCookieName: 'XSRF-TOKEN', // 默认值

// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

// `onUploadProgress` 允许为上传处理进度事件
// 浏览器专属
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},

// `onDownloadProgress` 允许为下载处理进度事件
// 浏览器专属
onDownloadProgress: function (progressEvent) {
// 处理原生进度事件
},

// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
maxContentLength: 2000,

// `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
maxBodyLength: 2000,

// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
// 则promise 将会 resolved,否则是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默认值
},

// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
// 如果设置为0,则不会进行重定向
maxRedirects: 5, // 默认值

// `socketPath` 定义了在node.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
// 只能指定 `socketPath` 或 `proxy` 。
// 若都指定,这使用 `socketPath` 。
socketPath: null, // default

// `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 }),

// `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: 'mikeymike',
password: 'rapunz3l'
}
},

// see https://axios-http.com/zh/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),

// `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(config)

这是最基础的请求方法,也是最全面的一种,能够配置的项目请看上面。

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<button @click="post">POST获取数据</button>
</div>
</template>

<script>
//引入axios
import axios from 'axios'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
const config={
method: 'get',
url:'http://httpbin.org/get'
}
axios(config)
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
post(){
const config={
method: 'post',
url:'http://httpbin.org/post',
data:{
name:'张三'
}
}
axios(config)
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
}
}
</script>





axios(url[, config])

这个方式和上面的一致,只是单独提出了url

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<button @click="post">POST获取数据</button>
</div>
</template>

<script>
//引入axios
import axios from 'axios'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
const config={
method: 'get'
}
axios('http://httpbin.org/get',config)
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
post(){
const config={
method: 'post',
data:{
name:'张三'
}
}
axios('http://httpbin.org/post',config)
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
}
}
}
</script>


axios.get(url[, config])

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
</div>
</template>

<script>
//引入axios
import axios from 'axios'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
axios.get('http://httpbin.org/get')
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
}
}
}
</script>


axios.post(url[, data[, config]])

<template>
<div id="app">
{{backdata}}
<br>
<button @click="post">POST获取数据</button>
</div>
</template>

<script>
//引入axios
import axios from 'axios'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
post(){
axios.post('http://httpbin.org/post',{
name:"张飞"
})
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
}
}
}
</script>


axios 合并请求

由于axios基于promise 所以也支持合并请求,不论是使用 promise.all 或者 axios.all 都是一样

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
</div>
</template>

<script>
//引入axios
import axios from 'axios'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
axios.all([axios({
method:'get',
url:'http://httpbin.org/get'
}),axios({
method:'get',
url:'http://httpbin.org/get'
})])
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
}
}
}
</script>


默认配置

如果有一些配置是公用的,可以使用默认配置来优化一些配置,默认配置在引入axios之后设置。

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<!-- <button @click="post">POST获取数据</button> -->
</div>
</template>

<script>
//引入axios
import axios from 'axios'
axios.defaults.baseURL="http://httpbin.org";
axios.defaults.timeout='2000';

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
axios.get('/get')
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
}
}
</script>

可以看出,设置了默认配置的 baseurl 之后,在调用的时候就不用使用完整的url地址了,只需要写接口部分。

TIP:默认配置是全局有效的,优先级没有单独配置的高,所以如果单独请求具有config,则默认配置相同的项目就会失效。


实例

在真实开发的时候,为了管理方便,我们一般会用实例来管理请求。每个实例都有自己的默认配置,直接调用实例来请求。

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<!-- <button @click="post">POST获取数据</button> -->
</div>
</template>

<script>
//引入axios
import axios from 'axios'

//新建实例
const server1 = axios.create({
baseURL:"http://httpbin.org",
timeout:'2000'
})
//实例外修改实例配置
server1.defaults.timeout='3000';

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
server1.get('/get')
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
}
}
</script>

可以看到,新建实例之后,调用的请求都是由实例发起。这样可以针对不同的服务器配置不同的请求配置。


拦截器

拦截器可以在请求或响应被 then 或 catch 处理前拦截它们。

//全局请求拦截器
axios.interceptors.request.use()
//全局响应拦截器
axios.interceptors.response.use()

//实例请求拦截器
实例名.interceptors.request.use()
//全局响应拦截器
实例名.interceptors.response.use()
//引入axios
import axios from 'axios'

//新建实例
const server1 = axios.create({
baseURL:"http://httpbin.org",
timeout:'2000'
})
//实例外修改实例配置
server1.defaults.timeout='3000';

//实例请求拦截器
server1.interceptors.request.use(config=>{
// 在发送请求之前做些什么
config.timeout='1000'
return config;
//注意,拦截处理完毕之后一定要返回config,否则请求会被中断.
},error=>{
// 对请求错误做些什么
return Promise.reject(error);
//返回错误,让请求中的catch()捕获
})

//实例响应拦截器
server1.interceptors.response.use(data=>{
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return data;
},error=>{
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
//返回错误,让请求中的catch()捕获
})
<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<!-- <button @click="post">POST获取数据</button> -->
</div>
</template>

<script>
//引入axios
import axios from 'axios'

//新建实例
const server1 = axios.create({
baseURL:"http://httpbin.org",
timeout:'2000'
})
//实例外修改实例配置
server1.defaults.timeout='3000';

//实例请求拦截器
server1.interceptors.request.use(config=>{
// 在发送请求之前做些什么
config.timeout='1000'
return config;
//注意,拦截处理完毕之后一定要返回config,否则请求会被中断.
},error=>{
// 对请求错误做些什么
return Promise.reject(error);
//返回错误,让请求中的catch()捕获
})

//实例响应拦截器
server1.interceptors.response.use(data=>{
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return data;
},error=>{
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
//返回错误,让请求中的catch()捕获
})


export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
server1.get('/get')
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
}
}
</script>


封装

为了更加方便安全的使用 axios ,一般也会对 axios 请求进行封装,这样避免了以后更换其他请求的时候每个文件都要修改的窘境。

在 src 目录下新建一个目录 network 用来保存请求接口封装文件,并在 network 目录下新建一个 io.js 接口文件。

//src/network/io.js

import axios from "axios";

//任意请求
export function request (config){
const request=axios.create(config)
//其他的同下
}

export function server1 (config){
//使用默认参数创建实例
const serve=axios.create({
baseURL:'http://httpbin.org/',
timeout:'2000'
})
//使用传入的其他参数发送请求
return serve(config);
}
//App.vue

<template>
<div id="app">
{{backdata}}
<br>
<button @click="get">GET获取数据</button>
<!-- <button @click="post">POST获取数据</button> -->
</div>
</template>

<script>
//引入封装好的请求接口文件
import {server1} from './network/io.js'

export default {
name: 'App',
data(){
return {
backdata:'这里将会显示数据'
}
},
methods:{
get(){
server1({
url:'get'
})
.then(data=>{
this.backdata=data;
})
.catch(err=>{
this.backdata="错误:"+data;
});
},
}
}
</script>



代码下载

下载地址:  密码:n8z7


转载请注明出处:http://gl.paea.cn/n.php?n=210
 
如您看得高兴,欢迎随意投喂,让我们坚持创作!
赞赏一个鸡腿
还没有人留下遗迹
综合 · 搜索