需要新建的目录和文件
.env.development 开发环境下的配置文件
VUE_APP_URL = 'http://api.testxxx.com/'
.env.production 生产环境下的配置文件
VUE_APP_URL = 'http://api.xxx.com/'
http.js
import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 10000 //请求超时时间
axios.defaults.baseURL = process.env.VUE_APP_URL //接口地址
// 请求拦截器
axios.interceptors.request.use(
(config) => {
// 请求正常则返回
if (config.method === 'post') {
config.data = qs.stringify(config.data)
}
// config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// config.headers['token'] = '111111111'
return config
},
(error) => {
// 请求错误则向store commit这个状态变化
return Promise.reject(error)
}
)
// 响应拦截器
axios.interceptors.response.use(
(response) => {
return response
},
(error) => {
return Promise.reject(error)
}
)
export default axios
request.js
import axios from './http'
// 封装post请求
export function post(url, params) {
return new Promise((resolve, reject) => {
axios
.post(url, params)
.then((req) => {
resolve(req.data)
})
.catch((error) => {
reject(error)
})
})
}
// 封装get请求
export function get(url, params) {
return new Promise((resolve, reject) => {
axios
.get(url, { params: params })
.then((req) => {
resolve(req.data)
})
.catch((error) => {
reject(error)
})
})
}
api.js (这个名可以根据功能分组来自定义多个文件,如login.js、user.js、vote.js)
import { get, post } from './request'
export const postLogin = (data) => {
return post('/backstage/Login/login', data)
}
index.js (如果在main.js里全局注册的话需要这个文件)
import * as api from './api'
import * as api from './login'
import * as api from './user'
import * as api from './vote'
const apiObj = {
...api,
...login,
...user,
...vote,
}
const install = function(Vue) {
if (install.installed) return
Object.defineProperties(Vue.prototype, {
$api: {
get() {
return apiObj
},
},
})
}
export default {
install,
}
main.js (如果全局注册的话在main.js里加)
import api from './api'
// 后台api接口 全局注册
Vue.use(api)
文件调用接口 (全局注册)
let data = {
name: this.name,
}
this.$api
.postLogin(data)
.then(res => console.log(res))
.catch(err => console.log(err))
文件调用接口 (非全局调用)
import { postLogin } from '@/utils/api.js'
let data = {
name: this.name,
}
postLogin(data)
.then(res => console.log(res))
.catch(err => console.log(err))