Vue+axios请求封装

1、请求源地址配置config.base.js

export default { "baseURL": "", "loginURL": "", "uploadImg": "/image/upload", "batchImageUpload": "/product/batchImageUpload/", "sentry": { "DSN": "", "version": "v1.0.0" } }

2、请求封装request.js

import axios from "axios" import Cookies from "js-cookie" import configfrom "../../config/config.base" let instance = axios.create({ headers: {content-type: application/json}, headers: {Authorization: Cookies.get("Authorization")} }) instance.defaults.baseURL = config.baseURL instance.defaults.withCredentials = true // 添加请求拦截器 instance.interceptors.request.use(function (config) { // 在发送请求之前做些什么 config.headers.channelToken = Cookies.get(channelToken) return config }, function (error) { // 对请求错误做些什么 return Promise.reject(error) }) // 添加响应拦截器 instance.interceptors.response.use(function (response) { // 对响应数据做点什么 if (response.status == "200") { if (response.data.code == "1001") { const loginUrl = Cookies.get("sysUrl") Cookies.remove("userName", { domain: "abc.com" }) Cookies.remove("token", { domain: "abc.com" }) localStorage.clear() window.location.href = loginUrl } } return response.data }, function (error) { // 对响应错误做点什么 console.log(--- 401 res error response ---) console.log(error.response) if(error && error.response && error.response.status == 401) { const loginUrl = Cookies.get("sysUrl") Cookies.remove("userName", { domain: "abc.com" }) Cookies.remove("token", { domain: "abc.com" }) localStorage.clear() window.location.href = loginUrl } return Promise.reject(error) }) export default instance

3、axios请求统一归类 api.js

import axios from "./request"

<1>不需要传参

// 获取渠道列表 export const getChannelList = () => { return axios({ url: "/classification/treeList/", method: "post", data: {} }) }

<2>需要传参

// 根据昵称和平台搜索评论内容 export const getSearchComment = (params) => { return axios({ url: "/searchComment/", method: "post", data: params }) }

4、在相应的vue文件中进行方法调用

<1>不需要传参

import {getChannelList} from ./api // 获取渠道列表 getChannelList().then((res) => { if(res.code == "201") { // console.log(res.body); this.query.channel = res.body } })

<2>需要传参

getSearchComment() {//自定义的方法 let params = { fromPlatform: this.searchPlatform,// 平台涞源 nickName: this.name,// 网名 pageSize: this.pagination.pageSize,// 每页几条数据 pageNum: this.pagination.pageNum,// 当前页数 } // 根据昵称和平台搜索评论内容 getSearchComment(params).then((res) => { if(res.code == "201"){ // console.log(res.body); this.tableData = res.body; this.pagination.totalCount = res.totalCount } }) // console.log(this.searchImgListDate) },