- Unified capture interface error
- Pop-up prompts
- Report an error redirect
- Basic authentication
- Form serialization
Functions implemented
- Unified capture interface error report: Used axios built-in interceptor
- Pop-up window tip: Introducing the Message component of the Element UI
- Error redirection: Router hook
- Basic authentication: server-side expiration timestamps and tokens, and also routing hooks
- Form serialization: I use qs (npm module) directly here, you can write it yourself if you have time
Usage and packaging
usage
// Service layer, import will find files in this directory by default. Some friends may not know about this// You can understand the theoretical concepts of the introduction of npm and es6 introductionimport axiosPlugin from "./server"; (axiosPlugin); rightaxiosPackage of(AXIOS: ) import axios from "axios"; import qs from "qs"; import { Message } from "element-ui"; import router from "../router"; const Axios = ({ baseURL: "/", // Because I did a reverse proxy locally timeout: 10000, responseType: "json", withCredentials: true, // Are cookies allowed headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" } }); //POST parameter serialization (add request interceptor)( config => { // Do something before sending the request if ( === "post" ) { // Serialization = (); // Warm reminder, if your company's submission can directly accept the json format, you can serialize it without qs } // If there is an authentication token, bring a token on the head // If you need to cross-site, it will be better to store cookies, and there are not so many restrictions. Some browsing environments restrict the use of localstorage // Here, localStorage is usually written to the local area after the request is successful, because it will be gone if you put it in vuex to refresh. // Some necessary data is written locally and read from locally if () { = ; } return config; }, error => { // The callback information of error depends on your company's definition Message({ // Ele.me's message pop-up component, similar to toast showClose: true, message: error && , type: 'error' }); return (); } ); //Return status judgment (add response interceptor)( res => { //Do something about the response data if ( && !) { Message({ // Ele.me's message pop-up component, similar to toast showClose: true, message: ? : , type: "error" }); return (); } return res; }, error => { // When the user logs in, he will get a basic information, such as user name, token, expiration time stamp //Drop localStorage or sessionStorage directly if (!("loginUserBaseInfo")) { // If the authentication information is not found during the interface access, return to the login page directly ({ path: "/login" }); } else { // If there is basic information, judge the timestamp and the current time. If the current time is greater than the server expiration time // Go back to the login page and log in again let lifeTime = (("loginUserBaseInfo")).lifeTime * 1000; let nowTime = new Date().getTime(); // Time stamp of the current time (nowTime, lifeTime); (nowTime > lifeTime); if (nowTime > lifeTime) { Message({ showClose: true, message: "Login status information expires, please log in again", type: "error" }); ({ path: "/login" }); } else { // Below is the satus for the interface callback. Because I made some error pages, they will point to the corresponding error page if ( === 403) { ({ path: "/error/403" }); } if ( === 500) { ({ path: "/error/500" }); } if ( === 502) { ({ path: "/error/502" }); } if ( === 404) { ({ path: "/error/404" }); } } } // Return the error message in the response let errorInfo = ? : ; return (errorInfo); } ); // Repackage the axios instance into a plugin, convenient (xxxx)export default { install: function(Vue, Option) { (, "$http", { value: Axios }); } };
Router hook adjustment (Router: )
import Vue from "vue"; import Router from "vue-router"; import layout from "@/components/layout/layout"; // There are a lot of sections, and the section is independent routing management, and it is all introduced by lazy loading.import customerManage from "./customerManage"; // Customer Managementimport account from "./account"; //Log inimport adManage from "./adManage"; // Advertising managementimport dataStat from "./dataStat"; // Statisticsimport logger from "./logger"; // logimport manager from "./manager"; // Managerimport putonManage from "./putonManage"; // Delivery managementimport error from "./error"; // Server errorimport { Message } from "element-ui"; (Router); // Please skip this paragraph and see the followingconst router = new Router({ hashbang: false, mode: "history", routes: [ { path: "/", redirect: "/adver", component: layout, children: [ ...customerManage, ...adManage, ...dataStat, ...putonManage, ...manager, ...logger ] }, ...account, ...error ] }); //Route Intercept// I almost forgot to explain that not all sections need authentication.// So I need authentication, I will add a field requireLogin when the route meta is set to true// This product must be authenticated. For example, if you don’t have login pages, you can access it directly!!!((to, from, next) => { if ((res => )) { // Determine whether login permission is required if (("loginUserBaseInfo")) { // Determine whether to log in let lifeTime = (("loginUserBaseInfo")).lifeTime * 1000; let nowTime = (new Date()).getTime(); // Time stamp of the current time if (nowTime < lifeTime) { next(); } else { Message({ showClose: true, message: "Login status information expires, please log in again", type: "error" }); next({ path: "/login" }); } } else { // If you are not logged in, jump to the login interface next({ path: "/login" }); } } else { next(); } }); export default router;
Some options that can be configured by axios, please refer to the official website for details.
export default { // Request address url: "/user", // Request type method: "get", // Please root path baseURL: "/api", // Data processing before request transformRequest: [function(data) {}], // Data processing after request transformResponse: [function(data) {}], // Custom request header headers: { "x-Requested-With": "XMLHttpRequest" }, // URL query object params: { id: 12 }, // Query object serialization function paramsSerializer: function(params) {}, // request body data: { key: "aa" }, // Timeout setting s timeout: 1000, // Whether tokens are included across domains withCredentials: false, // Custom request processing adapter: function(resolve, reject, config) {}, // Identity authentication information auth: { uname: "", pwd: "12" }, // Responsive data format json / blob /document /arraybuffer /text /stream responseType: "json", // xsrf settings xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", //Download and download progress callback onUploadProgress: function(progressEvent) { ( * 100 / ); }, onDownloadProgress: function(progressEvent) {}, // Maximum forwarding number, used for maxRedirects: 5, // Maximum response data size maxContentLength: 2000, // Customize the error status code range validateStatus: function(status) { return status >= 200 && status < 300; }, // For httpAgent: new ({ keepAlive: true }), httpsAgent: new ({ keepAlive: true }), // Used to set up cross-domain request proxy proxy: { host: "127.0.0.1", port: 8080, auth: { username: "aa", password: "2123" } }, // Used to cancel the request cancelToken: new CancelToken(function(cancel) {}) };
Summarize
Although this package is not a panacea version, I feel that most of my friends who use axios and vue can use it directly if they change it slightly
Authentication needs to be more rigorous, for example, tokens can follow the JWT specifications and introduce intermediate layer nodejs (intercept, encapsulation, decryption, and aggregation interface for transmission);
The above is the encapsulation (reporting errors, authentication, jumping, interception, prompts) in Vue that the editor introduced to you. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!