关于ajax的封装
程序员文章站
2022-04-14 11:29:55
env.js:/** * * baseUrl: 域名地址 * baseImgPath: 图片存放地址 * */let baseUrl = 'https://www.nbql.org.cn';let baseImgPath;var baseOrigin=window.location.origin;if(baseOrigin&&baseOrigin.includes('http')&&baseOrigin!='http://localhost:8080')...
env.js:
/**
*
* baseUrl: 域名地址
* baseImgPath: 图片存放地址
*
*/
let baseUrl = 'https://www.nbql.org.cn';
let baseImgPath;
var baseOrigin=window.location.origin;
if(baseOrigin&&baseOrigin.includes('http')&&baseOrigin!='http://localhost:8080'){
baseUrl=window.location.origin;
}
export {
baseUrl,
// routerMode,
baseImgPath
}
request.js:
import axios from 'axios';
import {
baseUrl
} from './env';
//自动切换环境
axios.defaults.baseURL = baseUrl; //默认请求地址
//设置超时时间
axios.defaults.timeout = 10000;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
//对外接口
export function request({
method,
url,
params
}) {
if (method == 'Get') {
return get(url, params);
} else if (method == 'Post') {
return post(url, params);
} else if (method == 'Upload') {
return upload(url, params);
}
}
// 封装get方法
function get(url, params) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
}).then(res => {
resolve(res.data);
}).catch(err => {
reject(err.data);
})
});
}
// 封装post方法
function post(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, QS.stringify(params)).then(res => {
resolve(res.data);
}).catch(err => {
reject(err.data);
})
});
}
// 封装upload方法
function upload(url, params) {
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
};
return new Promise((resolve, reject) => {
axios.post(url, params, config).then(res => {
resolve(res.data);
}).catch(err => {
reject(err.data);
})
});
}
service.js:
import {
request
} from '../config/request'
const xxxServer = { //自定义名称
xxxGet(params) { //get调用示例
return request({
method: 'Get',
url: '路径',
params: params
})
},
xxxUpload(params, flag) {
if (flag && flag == 1) { //upload示例
return request({
method: 'Upload',
url: '路径',
params: params
})
} else {
return request({
method: 'Post',
url: '路径',
params: params
})
}
},
xxxPost(params) { //post示例
return request({
method: 'Post',
url: '路径',
params: params,
})
}
}
export default xxxServer
实际调用:
import xxxServer from '路径'
xxxServer.xxxGet({参数}).then(res=>{
...
}).catch(err =>{
...
})
本文地址:https://blog.csdn.net/NBUT_King/article/details/107958613