第一种:
1.axios封装
import axios from "axios";
import qs from "qs";
import { catchError } from "../common/utils/catch_error";
// import Cookies from 'js-cookie';
import { Decrypt } from "../utils/jsdes";
axios.interceptors.response.use(
(response)=> {
return Promise.resolve(response);
},
(error) =>{
return Promise.reject(error);
}
);
axios.interceptors.request.use(
(config)=> {
// token = Cookies.get('token');
config.headers["Authorization"] =
"Bearer " + sessionStorage.getItem("token");
return config;
},
(error)=> {
return Promise.reject(error);
}
);
export async function initUrl(
url = "",
data = {},
type = "POST",
ContentType = "application/json"
) {
type = type.toUpperCase();
let res = await axios.request({
url: url,
method: type,
withCredentials: true, //跨域允许携带cookie
timeout: process.env.VUE_APP_BASE_SSO == "true" ? 2000000 : 20000, //生产20秒
params: type === "GET" || type === "DELETE" ? data : null,
data: type === "POST" || type === "PUT" ? qs.stringify(data) : null,
headers: { "Content-Type": ContentType },
});
if (res.status == 200 || res.status == 204) {
if (res.data.flag== "1" || res.data.flag== 1) {
//需要解密
let resData = Decrypt(res.data.data);
res.data.data = resData;
return Promise.resolve(res.data);
} else {
if (res.data.code == 0 && res.data.message) {
//解密message
let message = Decrypt(res.data.message);
res.data.message = message;
return Promise.resolve(res.data);
}
return Promise.resolve(res.data);
}
} else {
catchError(res.status);
}
}
2.使用
import { initUrl } from '@/config/axiosConfig';
export const login= (data) =>initUrl(`/api/login`, data, 'POST','application/x-www-form-urlencoded; charset=UTF-8');
//或
export const login= (data) =>initUrl(`/api/login`, data, 'POST');
第二种:
1.axios封装
import axios from 'axios';
import { catchError } from '../common/utils/catch_error';
import Cookies from 'js-cookie';
import { Decrypt } from '../utils/jsdes';
//网络请求配置.
export const qunInstance = axios.create({
baseURL: '',
timeout: process.env.VUE_APP_BASE_SSO == 'true' ? 2000000 : 20000, //生产20秒
});
// 请求拦截器
qunInstance.interceptors.request.use(
(config) => {
const token = sessionStorage.getItem('token');
if (!token && Cookies.get('token')) {
token = Cookies.get('token');
}
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
// config.headers['Content-Type'] = requestHeaders;
return config;
},
(error) => {}
);
// 响应拦截器
qunInstance.interceptors.response.use(
(res) => {
return Promise.resolve(res);
},
(error) => {
const { response } = error;
catchError(response);
}
);
export async function initUrl(url = '', data = {}, type = 'POST') {
type = type.toUpperCase();
if (type === 'GET') {
try {
let res = await qunInstance.get(url, {
params: data,
});
return new Promise((resolve) => {
try {
if (res.status == 200) {
if (res.data.flag == '1' || res.data.flag == 1) {
//需要解密
let resData = Decrypt(res.data.data);
res.data.data = resData;
resolve(res.data);
} else {
//解密message
if (res.data.code == 0 && res.data.message) {
let message = Decrypt(res.data.message);
res.data.message = message;
resolve(res.data);
return;
}
resolve(res.data); //不需要解密data
}
} else {
catchError(res);
}
} catch (error) {
resolve(res.data);
}
});
} catch (err) {
catchError(res);
}
} else if (type === 'POST') {
try {
let res = await qunInstance.post(url, data);
return new Promise((resolve) => {
if (res.status == 200) {
if (res.data.flag == '1') {
//需要解密
let resData = Decrypt(res.data.data);
res.data.data = resData;
// console.log(res.data)
resolve(res.data);
} else {
//解密message
if (res.data.code == 0 && res.data.message) {
let message = Decrypt(res.data.message);
res.data.message = message;
resolve(res.data);
return;
}
resolve(res.data); //不需要解密
}
} else {
catchError(res);
}
});
} catch (err) {
catchError(err);
}
}
}
}
2.使用
import { initUrl } from '@/config/axiosConfig';
export const login= (data) =>initUrl(`/api/login`, data, 'POST');
代理多个请求地址
1.vue.config
'use strict'
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = 'xxxx系统' // 网页标题
const port = 80 // 端口
module.exports = {
// publicPath: process.env.ENV === "production" ? "/dist/" : "/", //配置打包静态文件路径
publicPath: "/", //配置打包静态文件路径
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development', //设置是否在开发环境下每次保存代码时都启用 eslint验证。
productionSourceMap: false,
// webpack-dev-server 相关配置
devServer: {
// host: '0.0.0.0',
// port: port,
// open: true, //run serve 是否自动打开网页
proxy: {
[process.env.VUE_APP_BASE_API]: { //代理第一个地址
target: process.env.VUE_APP_BASE_URL,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: process.env.VUE_APP_BASE_API
},
// logLevel:'debug' //打印代理信息
},
[process.env.VUE_APP_BASE_API_TWO]: { //代理第二个地址
target: process.env.VUE_APP_BASE_URLTWO,
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API_TWO]: ''
},
// logLevel: 'debug'
},
// '/aTwo': {
// target: 'http://xx.xxxx.xxxx:8080',
// changeOrigin: true,
// pathRewrite: {
// '^/aTwo': ''
// },
// // logLevel:'debug'
// }
},
disableHostCheck: true //配置项用于配置是否关闭用于 DNS 重绑定的 HTTP 请求的 HOST 检查。 解决外部IP不能访问本地服务false
},
css: {
loaderOptions: { //用于向 CSS 相关的 loader 传递选项(设置)。
sass: {
sassOptions: {
outputStyle: "expanded"
}
}
}
},
// chainWebpack: config => { //打包分析
// config
// .plugin('webpack-bundle-analyzer')
// .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
// },
configureWebpack: {
name: name,
devtool: 'source-map',
externals: {
// 'AMap': 'AMap' // 高德地图
},
resolve: {
alias: {
'@': resolve('src')
}
},
plugins: [],
}
}
2…env.development 开发环境目录
# 页面标题
VUE_APP_TITLE = xxxx系统
# 开发环境配置
ENV = 'development'
# xxxx系统/开发环境
VUE_APP_BASE_URL = 'http://xx.xxxx.xx.xxxx:8080'
VUE_APP_BASE_URLTWO = 'http://xx.xxxx.xx.xxx:8888'
# url切换标志
VUE_APP_BASE_API = '/api'
VUE_APP_BASE_API_TWO = '/aTwo'
theirsBASE_URL = 'newxxx'
# 路由懒加载
VUE_CLI_BABEL_TRANSPILE_MODULES = true
# 是否开始平台统一登录
VUE_APP_BASE_SSO = true```
3.接口调用
import { initUrl } from '@/config/axios_config';
//代理执行第一个地址 'http://xx.xxxx.xx.xxxx:8080/api/user/info'
export const info= (data) => initUrl(`/api/user/info`, data, 'GET');
//代理执行第二个地址 'http://xx.xxxx.xx.xxx:8888/user/userinfo'
export const userinfo= (data) =>initUrl(`/aTwo/user/userinfo`,data, 'POST' );```