这里写目录标题
axios是一个基于promise的HTTP库,可以用在浏览器和node.js中,
使用:
1、引用
在线引用:
npm安装: npm install axios
在vue项目的main.js文件中引入axios
import axios from 'axios'
Vue.prototype.$axios = axios
2、axios 请求API
get params
post data
let baseUrl="https://xxxxx."
let api=baseUrl+"/login"
let data={
username:'fadfads',
code:'2545',
}
axios.get(api,{params:data}).then(res=>{
console.log(res)
})
axios.post(api,data).then(res=>{
console.log(res)
})
执行多个并发
const baseUrl="htpps://dfadfdf.ddd"
const apiUser=baseUrl+"/login"
const apiIndex=baseUrl+"/index"
const getUserInfo=()=>{
return axios.get(apiUser)
}
const getIndexInfo=()=>{
return axios.get(apiIndex)
}
axios.all([getUserInfo(),getIndexInfo()]).then(
axios.spread((userInfo,indexInfo)=>{
//2个请求执行完成
})
)
3、自定义配置:axios(config)
import axios from "axios";
axios.create({
timeout: 10000, //超时
url:'/login',//请求服务器url
// `headers` 是即将被发送的自定义请求头
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: 'get', // 是创建请求时使用的方法(默认)
baseURL: 'https://***.html/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
//由于使用的 form-data传数据所以要格式化
data = qs.stringify(data);
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
//即将与请求一起发送的 URL 参数,必须是一个无格式对象(plain object)或 URLSearchParams 对象
params: {
userId: 222
},
withCredentials: false, // 跨域请求时是否需要使用凭证(默认)
// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})
})
4、axios全局配置
import axios from "axios";
axios.defaults.withCredentials = true;
axios.defaults.timeout = 2000;
axios.defaults.baseURL = 'http://localhost:8080';
5、axios实例配置
let instance =axios.create({});
instance.defaults.timeout = 2000;
6、axios请求配置
axios.get('/user.json',{
timeout: 2000
}).then()
配置的优先级为:请求配置 > 实例配置 > 全局配置
7、拦截器
拦截器是在请求或响应被处理前拦截他
1)请求拦截器
const serve=axios.create({})
serve.interceptors.request.use(config=>{
//发生请求前的处理
return config
},(error)=>{
//请求错误处理
return Promise.reject(error)
})
2)响应拦截器
const serve=axios.create({})
serve.interceptors.response.use(config=>{
//请求成功对响应数据的处理
return config
},(error)=>{
//请求错误处理
return Promise.reject(error)
})
8、错误
axios.get('/login').then(res={
consloe.log(res)
}).catch((error)=>{
//请求拦截器和响应拦截器抛出错误时,返回的error对象会传给当前函数的error对象
console.log(error);
})
9、取消请求
const source=axios.CancelToken.source();
axios.get('/login',{cancelToken: source}).then(res={
consloe.log(res)
}).catch((error)=>{
//请求拦截器和响应拦截器抛出错误时,返回的error对象会传给当前函数的error对象
console.log(error);
})
//取消请求,参数可选,该参数信息会发送到请求的catch中
source.cancel('取消后的信息');
10、封装axios
1、新建一个request.ts
import qs from 'qs'
import axios, { AxiosRequestConfig, Method } from 'axios';
import { Loading,Message } from 'element-ui';
import { ElLoadingComponent } from 'element-ui/types/loading';
//1. 创建新的axios实例,
const serve = axios.create({
//baseURL: process.env.BASE_API, //公共接口
timeout: 10000,
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
});
let loadingInstance: ElLoadingComponent;
//2、请求拦截器
serve.interceptors.request.use(config =>{
loadingInstance = Loading.service({
text: '加载中',
background: 'rgba(0, 0, 0, 0.3)'
});
是否需要设置 token
const token = localStorage.getItem("token");//这里取token之前,你肯定需要先拿到token,存一下
if(token){
config.params = {'token':token} //如果要求携带在参数中
config.headers.token= token; //如果要求携带在请求头中
}
return config ;
},error=>{
return Promise.reject(error)
})
//响应拦截器
serve.interceptors.response.use(
response=>{
loadingInstance.close();
const errorCode = response?.data?.errorCode;
switch (errorCode) {
case '401':
// 根据errorCode,对业务做异常处理(和后端约定)
break;
default:
break;
}
return response;
},error=>{
loadingInstance.close();
const response = error.response;
// 根据返回的http状态码做不同的处理
switch (response?.status) {
case 401:
// token失效
break;
case 403:
// 没有权限
break;
case 500:
// 服务端错误
break;
default:
break;
}
return Promise.reject(response || {message: error.message})
}
);
//导出
export default serve;
2、新建一个api.ts
import serve from ‘./request’
export const queryMediaCount = (data:any)=> {
return serve({
url: ‘screen/queryMediaCount’,
method: ‘get’,
params: data,
})
}
或者新建一个http.ts
import serve from ‘./request’
const http ={
//methods: 请求
//@param url 请求地址
//@param params 请求参数
get(url,params){
const config = {
method: 'get',
url:url
}
if(params) config.params = params
return serve (config)
},
post(url,params){
const config = {
method: 'post',
url:url
}
if(params) config.data = params
return serve (config)
},
put(url,params){
const config = {
method: 'put',
url:url
}
if(params) config.params = params
return serve (config)
},
delete(url,params){
const config = {
method: 'delete',
url:url
}
if(params) config.params = params
return serve (config)
}
}
//导出
export default http
然后再新建一个api.ts
import http from ‘./http’
let resquest = “/testIp/request/”
/**
- @parms resquest 请求地址 例如:http://197.82.15.15:8088/request/…
- @param '/testIp’代表vue-cil中config,index.js中配置的代理
*/
// get请求
export function getListAPI(params){
return http.get(${resquest}/getList.json
,params)
}
// post请求
export function postFormAPI(params){
return http.post(${resquest}/postForm.json
,params)
}
// put 请求
export function putSomeAPI(params){
return http.put(${resquest}/putSome.json
,params)
}
// delete 请求
export function deleteListAPI(params){
return http.delete(${resquest}/deleteList.json
,params)
}
3、页面使用
import {toLoginOut,fmLogin}from “@/api/api”
const goLogout= async() =>{
const res=await toLoginOut()
if(res.type === “success”){
router.push({ path:‘/login’});
clearTimeout();
localStorage.clear()
}else{
ElMessage.error(res.message);
}
}