您的位置:首页 > 科技 > 能源 > axios在vue中的使用

axios在vue中的使用

2024/10/6 8:31:10 来源:https://blog.csdn.net/weixin_43676950/article/details/140341092  浏览:    关键词:axios在vue中的使用

文章目录

  • 一、axios是什么?
  • 二、使用步骤
    • 2.1 下载
    • 2.2 引入
    • 2.3 使用
      • Get请求
      • Post请求
      • Forms
  • 三、封装


一、axios是什么?

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

二、使用步骤

2.1 下载

npm install  axios -S

2.2 引入

import axios from 'axios'

2.3 使用

Get请求

import axios from 'axios'
// 向给定ID的用户发起请求
axios.get('/user?ID=12345').then(function (response) {// 处理成功情况console.log(response);}).catch(function (error) {// 处理错误情况console.log(error);}).finally(function () {// 总是会执行});// 上述请求也可以按以下方式完成(可选)
axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}).finally(function () {// 总是会执行});  // 支持async/await用法
async function getUser() {try {const response = await axios.get('/user?ID=12345');console.log(response);} catch (error) {console.error(error);}
}

Post请求

发起一POST请求

axios.post('/user',{firstName:'Fred',lastName:'Flintstone'
}).then(function(response){console.log(response);
}).catch(function(error)){console.log(error);
}

发起多个并发请求

function getUserAccount() {return axios.get('/user/12345');
}function getUserPermissions() {return axios.get('/user/12345/permissions');
}const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);// ORPromise.all([getUserAccount(), getUserPermissions()]).then(function ([acct, perm]) {// ...});

将HTML Form 转换JSON进行请求

const {data} = await axios.post('/user', document.querySelector('#my-form'), {headers: {'Content-Type': 'application/json'}
})

Forms

Multipart (multipart/form-data)

const {data} = await axios.post('https://httpbin.org/post', {firstName: 'Fred',lastName: 'Flintstone',orders: [1, 2, 3],photo: document.querySelector('#fileInput').files}, {headers: {'Content-Type': 'multipart/form-data'}}
)

URL encoded form (application/x-www-form-urlencoded)

const {data} = await axios.post('https://httpbin.org/post', {firstName: 'Fred',lastName: 'Flintstone',orders: [1, 2, 3]}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

三、封装

在src下创建utils目录,在该目录下创建文件 request.js

import axios from "axios";
import router from '../router/index'
// 1、创建axios对象
const service = axios.create({baseURL: 'http://localhost:9090/drsm',
});
//2、请求拦截器 
service.interceptors.request.use(config => {//在headers中加入认证信息。// if(token){//        config.headers['Token'] = token//    }return config
}, error => {Promise.reject(error);
})//响应拦截器
service.interceptors.response.use((response) => {//console.log(response);const {data} = response;if (data.code === 200 || data.code === 201) {//回传的数据return data;} else {return Promise.reject(new Error(data.message))}},error => {let msg;//console.log(error);if (error.response) {switch (error.response.status) {case 500:msg = "500-服务器发生错误,请及时联系管理员"break;case 404:msg = "404-你访问的页面不存在"break;case 401:msg = "401-请先登录系统,再完成操作"break;case 403:msg = "403-额...没有权限访问"breakdefault:msg = "555-发生错误,请及时联系管理员"break;}//登录界面发生错误时不跳转到错误页,if(error.config.url=='/login'){return Promise.reject(new Error(msg))}router.push({path: '/error',query: {msg: msg}});} else {msg = "连接不到目标服务器"}return Promise.reject(new Error(msg))}
)export default service;

在utils下创建api目录,接着创建文件 course.js

import qs from 'qs'
import service from '@/utils/request'export function loginReq(name, pwd) {const data = {username: name,password: pwd};return service.post('/login',qs.stringify(data));
}export function addUserReq(user){return service.post('/addUser',qs.stringify(user));
}export function userExist(username){let url = '/userExist/'+username;return service.get(url);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com