1)、创建目录和文件:utils/service.js,封装axios的请求拦截器和全局的配置,axios的post,get请求,
import axios from "axios"
// 创建axios 赋值给常量service
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 100000
headers: {
"Content-Type": "application/json;charset=UTF-8",
// "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
}
});
// 添加请求拦截器(Interceptors)
service.interceptors.request.use(function (config) {
// 发送请求之前做写什么
let token = localStorage.getItem("token");
// 如果有
if(token){
// 放在请求头(token跟后端沟通,他需要什么该成什么就可以了)
config.headers.authorization = token;
}
return config;
}, function (error) {
// 请求错误的时候做些什么
return Promise.reject(error);
});
// 添加响应拦截器
service.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default service
2)、创建api文件夹,
2.1)、index.js封装get和post请求
import service from "../utils/service";
export function POST(url, params) {
return new Promise((resolve, reject) => {
service.post(url, params)
.then(response => {
if (!response.data) {
resolve(response);
}
resolve(response.data);
}, err => {
reject(err);
})
.catch((err) => {
reject(err)
})
})
}
// get方法
export function GET(url, params) {
return new Promise((resolve, reject) => {
service.get(url, {
params
})
.then(response => {
resolve(response.data);
}, err => {
reject(err);
})
.catch((err) => {
reject(err)
})
})
}
2.2)、根据实际情况进行分模块:
如:home.js存放首页的所有请求
//home.js
import * as axiosBase from '@/api/index.js';
export let getBooks = function (params) {
params = params || {}
return axiosBase.GET('/api/books', params)
}
export let getBannerImgs = function (params) {
params = params || {}
return axiosBase.GET('/api/imgs', params)
}
如:users.js 存放登录注册相关的请求
//user.js
import * as axiosBase from '@/api/index.js';
export let checkUser = function (params) {
params = params || {}
return axiosBase.GET('/api/checkUser', params)
}
export let reg = function (params) {
params = params || {}
return axiosBase.POST('/api/users', params)
}
export let loginCheck = function (params) {
params = params || {}
return axiosBase.POST('/api/loginCheck', params)
}
//发送请求时,直接使用:this.$http.get(); 后 this.$http.post();