axios工具类封装:
// 引入axiosimport axios from 'axios';// 创建axios实例const httpService = axios.create({// url前缀-'http:xxx.xxx'// baseURL: process.env.BASE_API, // 需自定义baseURL:'http://localhost:80/',// 请求超时时间timeout: 3000 // 需自定义});//添加请求和响应拦截器// 添加请求拦截器httpService.interceptors.request.use(function (config) {// 在发送请求之前做些什么config.headers.token=window.sessionStorage.getItem('token');return config;}, function (error) {// 对请求错误做些什么return Promise.reject(error);});// 添加响应拦截器httpService.interceptors.response.use(function (response) {// 对响应数据做点什么return response;}, function (error) {// 对响应错误做点什么return Promise.reject(error);});/*网络请求部分*//* *get请求 *url:请求地址 *params:参数 * */export function get(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'get',params: params}).then(response => {resolve(response);}).catch(error => {reject(error);});});}/* *post请求 *url:请求地址 *params:参数 * */export function post(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'post',data: params}).then(response => {console.log(response)resolve(response);}).catch(error => {console.log(error)reject(error);});});}/* *文件上传 *url:请求地址 *params:参数 * */export function fileUpload(url, params = {}) {return new Promise((resolve, reject) => {httpService({url: url,method: 'post',data: params,headers: { 'Content-Type': 'multipart/form-data' }}).then(response => {resolve(response);}).catch(error => {reject(error);});});}export default {get,post,fileUpload}
配置@作为根目录
vue.config.js里面配置:
configureWebpack:{resolve:{alias:{'@':resolve('src')}}},
导入axios工具类;
import axiosUtil from '@/util/axios'
改下:
try{let result=await axiosUtil.post("adminLogin",form.value);let data=result.data;if(data.code==0){ElMessage.success("登录成功");window.sessionStorage.setItem("token",data.token);}else{ElMessage.error(data.msg);}}catch(err){console.log("error:"+err);ElMessage.error("系统运行出错,请联系管理员");}