引入文件方式:axios写接口
引入文件:axios调用接口1.axios.js文件2.写post、get接口3.调用接口1.axios.js文件import axios from 'axios'import { Loading, Message } from 'element-ui'// 引入Loading服务// 创建 axios 实例const service = axios.create({})// 开始加载动画let
·
引入文件:axios调用接口
1.axios.js文件
import axios from 'axios'
import { Loading, Message } from 'element-ui'// 引入Loading服务
// 创建 axios 实例
const service = axios.create({
})
// 开始加载动画
let loading
function startLoading() {
loading = Loading.service({
lock: true, // 是否锁定
text: '正在交互...', // 加载中需要显示的文字
background: 'rgba(0,0,0,.7)'// 背景颜色
})
}
// 结束加载动画
function endLoading() {
loading.close()
}
// request interceptor
service.interceptors.request.use(config => {
var tokenjava = localStorage.getItem('tokenjava')
var token = localStorage.getItem('token')
startLoading()
// alert('qingqiu')
if (token) {
config.headers[ 'api_key' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
}
if (tokenjava) {
config.headers[ 'api_key' ] = tokenjava // 让每个请求携带自定义 token 请根据实际情况自行修改
}
// if (token) {
// config.headers[ 'api_key' ] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJMb2dpblRpbWVcIjpcIjIwMjEtMDEtMjggMTY6MTI6NDFcIixcIk9pZFwiOlwiMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAxXCJ9In0.HLCV0r7KP3rOpyWbLuvGYXo1uaAPQ_-lON03QWxoMAA'
// }
// if (tokenjava) {
// config.headers[ 'api_key' ] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJMb2dpblRpbWVcIjpcIjIwMjEtMDEtMjggMTY6MTI6NDFcIixcIk9pZFwiOlwiMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAxXCJ9In0.HLCV0r7KP3rOpyWbLuvGYXo1uaAPQ_-lON03QWxoMAA'
// }
return config
}, (error) => {
return Promise.reject(error)
})
// 相应拦截
service.interceptors.response.use(response => {
// alert('end')
endLoading()// 结束加载动画
return response // 结束时把response return回去
}, error => {
// 错误提醒
endLoading()// 如果错误也结束动画
Message.error(error.response.data)
return Promise.reject(error)
})
export { service as axios }
2.写post、get接口
@/api/api.js
import { axios } from './axios'
const base = 'http://xxx.xxx.x.xxx:xxxx/'
const base3 = window.ApiConfig.base
export const getMenuList = params => { return axios.get(`${base}api/System/PortalMenu_GetAllData`, { params: params }) }
export const addPaperType = params => { return axios.post(`${base}api/System/PortalMenu_SaveData`, params).then(res => res.data) }
3.调用接口
<script>
import { getMenuList } from '@/api/api'
export default {
...
methods: {
initData(){
getMenuList().then(res=>{...})
}
}
...
}
</script>
更多推荐
已为社区贡献2条内容
所有评论(0)