(1)在src下创建request/api.js文件
import axios from 'axios'
import qs from 'qs'
const request = axios.create({
baseURL: '你的域名',
timeout: 1000,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
})
request.interceptors.request.use(function (config) {
return config
}, function (error) {
return Promise.reject(error)
})
request.interceptors.response.use(function (response) {
return response.data
}, function (error) {
return Promise.reject(error)
})
export function postApi (data) {
return request({
url: '后台接口地址',
method: 'post',
data: qs.stringify(data)
})
}
export function getApi (data) {
return request({
url: '后台接口地址',
method: 'post',
data: qs.stringify(data)
})
}
(2)main.js中引入
import * as api from './request/api.js'
Vue.prototype.$api = api
(3)页面使用 引入api中的方法直接调用
import { postApi ,getApi } from '@/request/api'
let data = {type: 'resourcesType'}
postApi (data).then(res => {
console.log(res)
}).catch(res => {
console.log(res)
})