1. vue安装axios
npm install axios -S
或者
npm i axios -S
2. 在main.js进行全局引入
import axios from 'axios'
Vue.prototype.$axios = axios
3. 配置跨域 在根目录下vue.config.js里边
module.exports = {
publicPath: './',
devServer: {
open: true,
https: false,
hotOnly: false,
proxy: {
'/api': {
target: 'http://********',
ws: true,
secure: false,
changOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
before: app => { }
}
}
4. 在src子目录下的api文件夹下创建request.js文件进行简单的封装axios
import axios from 'axios'
import {
Message,
Loading
} from "element-ui";
import qs from 'qs'
var isPro = process.env.NODE_ENV === "production"
let baseURL = isPro ? "/weixin-api" : "/api"
const service = axios.create({
baseURL: baseURL,
timeout: 30000
})
let loading = "";
service.interceptors.request.use(
(config) => {
if (!(config.headers['Content-Type'])) {
loading = Loading.service({
lock: true,
text: "加载中...",
spinner: "el-icon-loading",
background: "rgba(255,255,255,0.7)",
customClass: "request-loading",
});
if (config.method == 'post') {
config.headers['Content-Type'] =
'application/x-www-form-urlencoded;charset=UTF-8'
for (var key in config.data) {
if (config.data[key] === '') {
delete config.data[key]
}
}
config.data = qs.stringify(config.data)
} else {
config.headers['Content-Type'] =
'application/x-www-form-urlencoded;charset=UTF-8'
}
}
const token = "token"
if (token) {
config.headers['Authorization'] = token
}
return config
},
(error) => {
loading.close();
console.log('发送失败', error)
return Promise.reject(error)
}
)
service.interceptors.response.use(
(response) => {
loading.close();
const dataAxios = response.data
return dataAxios
},
(error) => {
Message({
message: error,
type: 'error',
duration: 3 * 1000
})
loading.close();
return Promise.reject(error)
}
)
export default service
5. 在api文件夹下创建apis文件
import axios from "./request";
let reportupload= '/report/upload';
export const reportUpload= (params) => {
return axios.get(reportupload, {
params: params
})
}
let reportupload= '/report/upload';
export const reportUpload= (data) => {
return axios.post(reportupload, data)
}
6. 在页面中调用接口
import { reportUpload } from "@/api/apis.js";
async uploadBackCall() {
try{
let res = await reportUpload();
console.log(res)
}catch{
}finally{}
},