vue+axios拦截处理、简单二次封装
程序员文章站
2022-03-26 17:08:40
代码http.jsimport Vue from 'vue'import { Loading,Message } from 'element-ui';// 防止一开始弹出提示框Vue.component(Message.name, Message);//axios 设置import axios from 'axios'axios.defaults.timeout = 180000; //3min超时//默认网关-计划系统网关const BASE_API = "/api/myclient...
代码
http.js
import Vue from 'vue' import { Loading,Message } from 'element-ui'; // 防止一开始弹出提示框 Vue.component(Message.name, Message); //axios 设置 import axios from 'axios' axios.defaults.timeout = 180000; //3min超时 //默认网关-计划系统网关 const BASE_API = "/api/myclient"; //http request 拦截器 axios.interceptors.request.use( config =>{ config.headers = { 'Authorization': localStorage.getItem('token'), // token 'Content-Type':'application/json' }; return config },error => { Message.error('http_request_error:'+JSON.stringify(error)); return Promise.reject(error) } ); //http response 拦截器 axios.interceptors.response.use( response =>{ return response.data; }, error =>{ Message.closeAll(); Message.error('http_response_error:'+JSON.stringify(error)); return Promise.reject(error); } ); const http = { // get 默认每个接口请求显示loading,放在这里统一处理loading get: (url, params = {}, prefixUrl = BASE_API, loading = true) => { return new Promise((resolve, reject) => { let model; if (loading) { model = Loading.service({fullscreen: true}); } axios.get(prefixUrl + url, { params: params }).then(response => { if (model) model.close(); // 接口数据处理状态code为200,用then接收,不是200,用catch接收 if (response.code == 200) { resolve(response) } else { // Message.error(response.message || '系统错误请联系管理员'); reject(response) } }).catch(error => { if (model) model.close(); console.error('axios_get_error',error) }) }) }, // post post: (url, params = {}, prefixUrl = BASE_API, loading = true) => { let model; if (loading) { model = Loading.service({fullscreen: true}); } return new Promise((resolve, reject) => { axios.post(prefixUrl + url, JSON.stringify(params)).then(response => { if (model) model.close(); if (response.code == 200) { resolve(response) } else { // Message.error(response.message || '系统错误请联系管理员'); reject(response) } }).catch(error => { if (model) model.close(); console.error('axios_post_error',error) }) }) } }; // 适用于vue2,绑定到vue原型上 Vue.prototype.$http = http; // 用于vuex或其他的单独js里的调用,不用的话注释掉 module.exports = { $get:http.get, $post:http.post, };
api代理
前后端开发的时候,如果连接的接口地址在其他同事电脑上,则需要在vue.config.js
里设置api代理。
module.exports = { devServer: { proxy: { '/api' : { //代理api target: "测试服务器地址",// 代理接口(注意只要域名就够了) changeOrigin: true,//是否跨域 ws: true, // proxy websockets pathRewrite: {//重写路径 "^/api": ''//代理路径 } }, } } }
应用
vue组件内
let p = { cityCode: '', projectName: '测试项目', }; this.$http.post('/project/add', p).then((res) => { this.$message.success('新增成功'); }).catch((res)=>{ this.$message.warning('项目名称不能重复'); });
本文地址:https://blog.csdn.net/qq_32886245/article/details/109033344
上一篇: 玄武门事变之前,李世民的实力有多恐怖?