以上为封装用到的文件:
1:.vue 页面 请求接口:
import { getAll } from "@/api/httpPost" //需要引入接口统一配置文件
export default { data() { return { datainfo:{ key:value } } } mounted() { getAll(this.datainfo).then(res => { //datainfo 为data里面的数据对象体 console.log(res) //res 为接口返回的数据体 }) } } 2:httpPost.js 把项目用到的接口请求统一放入一个文件,方便接口地址维护 import request from '@/utils/request' //引入request.js axios请求文件//获取所有菜单 export function getAll(data) { //data 为请求参数对象 return request({ url: '/services/hos/getAll', //基础url地址 method: 'post', data:data //data 为请求参数对象 }) } 3:request.js 文件 最终的axios请求
import vue from "vue"; import axios from "axios"; const service = axios.create({ timeout: 5000 // request timeout }); // request interceptor service.interceptors.request.use( config => { // 请求体数据添加 基础访问url if (config) { config = { ...config, baseURL: vue.prototype.appConfig.SERVER_ADDRESS //写在config.json 配置文件里面的后端ip端口号地址 }; // 请求体数据添加 Token if (config.data && !(config.data instanceof FormData)) { const formData = new FormData() if (!config.data.sessionId) { // config.data.sessionId = getToken() } formData.append("requestJson", JSON.stringify({ ...config.data })) // config.data = formData config.data = "requestJson="+JSON.stringify(config.data) //针对后端 @FormParam(value = "requestJson") 格式接收参数 //如果是@requestBody 则 config.data = config.data 或者不需要多余的步骤 } else if (config.data instanceof FormData) { const formData = new FormData() if (!config.data.has("sessionId")) { // config.data.append("sessionId", getToken()) } formData.append("requestJson", JSON.stringify({ ...config.data })) config.data = formData } else { const formData = new FormData() if (config.data) { if (!config.data.sessionId) { // config.data.sessionId = getToken() } } else { // config.data = { sessionId: getToken() } } formData.append("requestJson", JSON.stringify({ ...config.data })) config.data = formData } } return config; }, error => { return Promise.reject(error); } ); // response interceptor //接口返回 service.interceptors.response.use( response => { const res = response.data; // if the custom code is not 20000, it is judged as an error. if (res.code !== 20000 && response.status !== 200) { // Message({ // message: res.message || "Error", // type: "error", // duration: 5 * 1000 // }); // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired; if (res.code === 50008 || res.code === 50012 || res.code === 50014) { // to re-login // MessageBox.confirm( // "You have been logged out, you can cancel to stay on this page, or log in again", // "Confirm logout", // { // confirmButtonText: "Re-Login", // cancelButtonText: "Cancel", // type: "warning" // } // ).then(() => { // store.dispatch("user/resetToken").then(() => { // location.reload(); // }); // }); } return Promise.reject(new Error(res.message || "Error")); } else { return res; } }, error => { return Promise.reject(error); } ); export default service;
4:config.json IP端口号 配置文件
{ "//": "后台服务地址", "SERVER_ADDRESS": "http://192.168.22.54:8081", "SERVER_URL": "http://test.00.cn" }