Axios的使用
Axios
axios中文网站: https://www.axios-http.cn/docs/intro vue对axios介绍使用: https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html axios是vue官方推荐的一HTTP库 Axios是一个基于promise的HTTP库
基本使用
1.在项目中安装axios npm install axios 2.在项目中导入 import axios from 'axios'; 3.以get方式进行请求(注意跨域问题) axios.get('请求地址').then(res=>{ // 因为是promise封装的 console.log(res); // 响应的数据 }).catch(error=>{ console.log(error); // 发生报错 }).finally(()=>{ console.log(123456); // 无论是有响应数据还是报错都会执行当前方法 })
vue2为例
import Vue from 'vue' import App from './App.vue' import axios from 'axios'// 1.导入axios包 Vue.config.productionTip = false Vue.prototype.$http = axios // 2.全局挂载 new Vue({ render: h => h(App), }).$mount('#app') 1.发送get请求 this.$http.get('http://127.0.0.1:5000/').then(res=>{ console.log(res); // 响应的数据 }).catch(error=>{ console.log(error); // 发生报错 }).finally(()=>{ console.log(123456); // 无论是有响应数据还是报错都会执行当前方法 }) 2.get方式携带参数 this.$http.get('http://127.0.0.1:5000/',{ params: { ID: 12345 } }).then(res=>{ console.log(res); }).catch(error=>{ console.log(error); }).finally(()=>{ console.log(123456); }) // 'http://127.0.0.1:5000/?ID=123456 2.发送post请求并且携带参数 this.$http.post('http://127.0.0.1:5000/',{ID: 12345}).then(res=>{ console.log(res); }).catch(error=>{ console.log(error); }).finally(()=>{ console.log(123456); })
axios的默认配置
{ // `url` 是用于请求的服务器 URL url: '/user', // `method` 是创建请求时使用的方法 method: 'get', // default // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。 // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data, headers) { // 对 data 进行任意转换处理 return data; }], // `transformResponse` 在传递给 then/catch 前,允许修改响应数据 transformResponse: [function (data) { // 对 data 进行任意转换处理 return data; }], // `headers` 是即将被发送的自定义请求头 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即将与请求一起发送的 URL 参数 // 必须是一个无格式对象(plain object)或 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', 和 'PATCH' // 在没有设置 `transformRequest` 时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 浏览器专属:FormData, File, Blob // - Node 专属: Stream data: { firstName: 'Fred' }, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 `timeout` 的时间,请求将被中断 timeout: 1000, // `withCredentials` 表示跨域请求时是否需要使用凭证 withCredentials: false, // default // `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) { }) }
axios的封装
一般存放在vue项目中的api文件下的reuqest.js中 1.需要在main.js进行注册 import Vue from 'vue' import App from './App.vue' import axios from 'axios'// 导入axios包 Vue.config.productionTip = false Vue.use(axios) // 挂载 在项目中导入 ... 2.创建一个api/request.js文件导入axios import axios from 'axios' import {Message} from 'element-ui' //ui组件 import store from '@/store' // vuex import {getToken} from '@/utils/auth' // token 3.创建axios实例 const service = axios.create({ baseURL: process.env.BASE_API, // api的base_url(固定的url对象 例如:http:127.0.0.1/api/v1) timeout: 5000 // 请求超时时间 }) 4.创建axios的 请求拦截器 与 响应拦截器 4.1.request拦截器 请求 拦截器 给 后端的 service.interceptors.request.use(config => { //config请求获取的对象 // 在发送请求之前 将token携带 if (store.getters.token) { // 判断vuex状态中的token值 config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改 } return config }, error => { // 请求出现的错误都,获取错误信息,将错误信息放入promise对象中错误中 console.log(error) Promise.reject(error) }) 4.2.respone拦截器 响应拦截器 发来的 service.interceptors.response.use( response => response, //响应获取的对象 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中 // const res = response.data; // if (res.code !== 20000) { // Message({ // message: res.message, // type: 'error', // duration: 5 * 1000 // }); // // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了; // if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', { // confirmButtonText: '重新登录', // cancelButtonText: '取消', // type: 'warning' // }).then(() => { // store.dispatch('FedLogOut').then(() => { // location.reload();// 为了重新实例化vue-router对象 避免bug // }); // }) // } // return Promise.reject('error'); // } else { // return response.data; // } error => { console.log('err' + error)// for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) }) 4.3.抛出一个axios的对象 可以进行使用 export default service 5.使用抛出axios的对象创建请求函数 import service from '@/api/reuqest' // 导入axios实例对象 5.1 get export function getInfo(data) { //使用,抛出一个请求后端数据的函数并且携带参数 return service({ url: '/user/info', method: 'get', params:data }); } 5.2.post export function Postuser(data){ return service({ url:"/", method: 'post', data:data }) } 6.在vue组件中进行导入使用 import { getInfo } from '@/api/user' 6.1.get getInfo('数据').then(res=>{ console.log(res); // 获取正确的请求内容 }).catch(error=>{ console.log(error); // 如果请求报错就会接收到错误的信息需要进行处理(无论是请求拦截器还是响应拦截器) }).finally(()=>{ console.log('无论怎么样都会执行'); })
补充部分
import axios from 'axios' const service = axios.create({ baseURL: 'http://127.0.0.1:8000/', // api的base_url(固定的url对象 例如:http:127.0.0.1/api/v1) timeout: 5000 // 请求超时时间 }) service.interceptors.request.use(config => { return config }, error => { console.log(error) Promise.reject(error) }) service.interceptors.response.use( response => { const res = response.data; console.log(res); console.log(response); 进行处理 除200 以外的定制的别的状态码 相应状态码是200的内容 return response.data //接受后端的返回的内容 }, error => { // 如果出现错误那么将错误存储 // console.log('err' + error)// for debug return Promise.reject(error) // 将响应拦截的错误放在Promise的对象中进行返回,调用axios 可以通过catch接受到错误 }) export function get_api(){ return service({ url:'api/v1/api/', method:'get' }) } get_api().then(res=>{ // 当后端抛出异常时,会被响应拦截器拦截将错误信息存放到错误容器中, console.log(res); // 被捕获到错误后 这里就没有内容 }).catch(error=>{ // 从这个理将错误信息抛出 console.log('err' + error) console.log(error.response.data.error); console.log(error.response.status); })
本文作者:_wangkx
本文链接:https://www.cnblogs.com/kaixinblog/p/17878642.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南