API封装
// api.js
//包含 element-ui 做loading处理
import axios from 'axios';
import {Loading} from 'element-ui';
import router from '@/router'
axios.defaults.baseURL = 'http://www.baidu.com/'
axios.defaults.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
export default {
post: function (url, params) {
const loading = Loading.service({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
return new Promise((resolve, reject) => {
axios.post(url, params).then(response => {
resolve(response.data)
loading.close();
}).catch(err => {
reject(err)
loading.close();
router.push({path: '/404'})
})
})
}
}
//含拦截器和token
import axios from 'axios';
axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'http://www.baidu.com'
//http request 拦截器
axios.interceptors.request.use(
config => {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'token': localStorage.getItem('token') // 获取token缓存
}
return config;
},
error => {
return Promise.reject(error);
}
);
export default {
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/
get: function (url, params = {}) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
},
/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/
post: function (url, data) {
return new Promise((resolve, reject) => {
axios.post(url, data)
.then(response => {
resolve(response.data);
}, err => {
reject(err)
})
})
}
}
使用
import Api from "../../api.js";
import qs from "qs";
let data={userName:'liming'}
Api.post("/api/url", qs.stringify(data)).then(response => {
if (response == '200') {
} else {
}
});
// 后台需要json数组字符串,前端封装json数组字符串,
//解决后台拿不到数据两种方法
// 第一种
let postData = new URLSearchParams()
postData.append('questionStr', JSON.stringify(that.questionStr))
//第二种
import qs from "qs";
qs.stringify(data) //qs插件
//还有一种可能就是请求头,post请求一般为 'application/x-www-form-urlencoded'
let headers = {
'content-type': method == 'POST' ?
'application/x-www-form-urlencoded' : 'application/json',
'stkjtoken': token
}
代理跨域
//新建vue.config.js
module.exports = {
publicPath: "./", //新版本, 不修改打包后用不了
devServer: {
proxy: {
'/api': {
target: 'http://www.baidu.com'
},
}
},
};