preface
Thanks to the selfless dedication of everyone on the Internet, follow the footsteps of the big guy, to rapid growth.
Front-end login interception
Front-end login interception is divided into two parts: route interception and HTTP interception
Routing to intercept
When defining a route, add a custom requireAuth field to determine whether the access to the route requires a login. If the user has logged in, the route is successfully entered; otherwise, the login page is displayed.
const routes = [
{
path: '/'.name: '/'.component: Index
},
{
path: '/repository'.name: 'repository'.meta: {
requireAuth: true.// Add this field to indicate that login is required to enter this route
},
component: Repository
},
{
path: '/login'.name: 'login'.component: Login
}];
// after defining the route, we use the hook function provided by vue-router to determine the route beforeEach().
router.beforeEach((to, from, next) = > {
if (to.meta.requireAuth) { // Determine whether the route requires login permission
if (store.state.token) { // Check whether the current token exists through vuex state
next();
}else {
// if it has whiteList, make a judge
if(whiteList.indexOf(to.path) ! = = -1) {
// in the free login whitelist, go directly
next()
} else {
// Other pages that do not have permission to access are redirected to the login page. // Set the redirect route path as a parameter and redirect to the redirect route after successful login
next(`/login? redirect=${to.path}`)
/ / or:
next({
path: '/login'.query: {redirect: to.fullPath}
})
}
}
}else{ next(); }})Copy the code
http
intercept
Tokens have three states
- There is no value
- Valid
- Valid, expired
What the token does: Acts as a pass when interacting with the backend.
HTTP interception falls into two categories:
- Request to intercept
- The response to intercept
[1] Request interception: If there is a local token, request headers to add the token field before sending the request. [2] Response interception: The current token is invalid, but the token is still stored locally. When you access an interface that requires login permissions, you should actually ask the user to log in again. In this case, we need to combine the HTTP status code returned by the HTTP interceptor and the back-end interface to judge.
/** AXIos encapsulates request interception, corresponding interception, unified error handling */
import axios from 'axios';import QS from 'qs';
import { Toast } from 'vant';
import store from '.. /store/index'
// Environment switch
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = '/api';
} else if (process.env.NODE_ENV == 'debug') {
axios.defaults.baseURL = ' ';
} else if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'http://api.123dailu.com/';
}
// Request timeout
axios.defaults.timeout = 10000;
// Post request header
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
// Request interceptor
axios.interceptors.request.use(
config= > {
// Check whether the token exists before each request is sent. If the token exists, add the token to the header of the HTTP request
// Even if the token exists locally, it is possible that the token is expired, so the return status is determined in the response interceptor
const token = store.state.token;
token && (config.headers.Authorization = token);
return config;
},
error= > {
return Promise.error(error);
})
// Response interceptor
axios.interceptors.response.use(
response= > {
if (response.status === 200) {
return Promise.resolve(response);
} else {
return Promise.reject(response); }},// The server status code is not 200
error= > {
if (error.response.status) {
switch (error.response.status) {
// 401: Not logged in
// If you do not log in, the login page is displayed and the path of the current page is displayed
// Return to the current page after successful login. This step must be performed on the login page.
case 401:
router.replace({
path: '/login'.query: { redirect: router.currentRoute.fullPath }
});
break;
// 403 Token expired
// Prompts the user when the login expires
// Clear local tokens and vuEX token objects
// Go to the login page
case 403:
Toast({
message: 'Login expired, please log in again'.duration: 1000.forbidClick: true
});
/ / remove the token
localStorage.removeItem('token');
store.commit('loginSuccess'.null);
// Jump to the login page and upload the fullPath of the page to be accessed. After successful login, jump to the page to be accessed
setTimeout(() = > {
router.replace({
path: '/login'.query: {
redirect: router.currentRoute.fullPath
}
});
}, 1000);
break;
// 404 request does not exist
case 404:
Toast({
message: 'Network request does not exist'.duration: 1500.forbidClick: true
});
break;
// Other errors, directly throw error message
default:
Toast({
message: error.response.data.message,
duration: 1500.forbidClick: true
});
}
return Promise.reject(error.response); }});/** * get method, corresponding to get request *@param {String} Url [requested URL address] *@param {Object} Params [parameter taken with request] */
export const get =(url, ... params) = >{
return new Promise((resolve, reject) = >{
axios.get(url, {
params: params
})
.then(res= > {
resolve(res.data);
})
.catch(err= > {
reject(err.data)
})
});
}
/** * Post method, corresponding to post request *@param {String} Url [requested URL address] *@param {Object} Params [parameter taken with request] */
export const post = (url,... params) = >{
return new Promise((resolve, reject) = >{ axios.post(url, QS.stringify(... params)) .then(res= > {
resolve(res.data);
})
.catch(err= > {
reject(err.data)
})
});
}
Copy the code
Reference links:
- www.jianshu.com/p/646ed4edf…
- Juejin. Cn/post / 685457…