A project learned to implement login, block, logout functions with VUE family buckets + AXIos, and intercept requests and responses using AXIos’s HTTP interceptor.
preface
This project uses Github’s Personal token as a login token to access your Repository List. Through this project, I learned how to realize the login and interception, logout, token invalidation interception and the corresponding use of AXIos interceptor needed in a front-end project.
Prepare the Github Personal Token you need to generate your own. Access Demo after Token generation to view your Repository List.
. ├ ─ ─ the README. Md ├ ─ ─ dist / / package build folder after │ ├ ─ ─ build. Js │ └ ─ ─ build. Js. Map ├ ─ ─ index. The HTML ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ App. Vue │ ├ ─ ─ assets │ │ ├ ─ ─ CSS. The CSS │ │ ├ ─ ─ icon. The CSS │ │ └ ─ ─ logo. The PNG │ ├ ─ ─ constant │ │ └ ─ ─ API. Js / / configuration API interface file │ ├ ─ ─ │ ├─ index.vue │ ├─ login.vue │ ├─ main.js │ ├─ repository │ ├─ ├─ class.js // vuex types ├─ class.js // │ ├─ class.js
Copy the code
Technology stack
- Vue 2.0
- vue-router
- vuex
- axios
- vue-material
Step 1: Route interception
First of all, a customized requireAuth field should be added when defining the route, which is used to determine whether the access of the route requires 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.//If this field is added, login is required to enter the route
},
component: Repository
},
{
path: '/login',
name: 'login',
component: Login
}
];Copy the code
After defining the route, we use the hook function beforeEach() provided by vue-Router to determine the route.
router.beforeEach((to.from.next) = > {
if (to.meta.requireAuth) { //Check whether the route requires login permission
if (store.state.token) { //Check whether the current token exists by using the VUex state command
next(a); }else {
next({
path: '/login',
query: {redirect: to.fullPath} //Set path as a parameter to redirect to this route after successful login}}})else {
next();
}
})Copy the code
Each hook method takes three arguments:
- To: Route: indicates the destination Route to be entered
- From: Route: indicates the Route that the current navigation is about to leave
- Next: Function: Be sure to call this method to resolve the hook. The execution depends on the call parameters of the next method.
- Next (): Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
- Next (false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.
- Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed.
Make sure you call the next method or the hook won’t be resolved.
See/SRC /router.js for the complete method
To.meta is our custom data, including the requireAuth field we just defined. Use this field to determine whether the route requires login permission. If the application does not have a token, the login page is displayed for login. After the login succeeds, the system switches to the target route.
Does login interception end here? Don’t. This approach is simple front-end routing control and does not really prevent users from accessing routes that require login permission. There is also a case where the current token expires, but the token is still stored locally. When you access a route that requires login permission, 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.
To process all HTTP requests and responses uniformly, use axios’s interceptor. When the HTTP Response Eptor is configured, the back-end interface returns 401 Unauthorized so that users can log in again.
//HTTP Request interceptor
axios.interceptors.request.use(
config = > {
if (store.state.token) { //Determines whether a token exists, and if so, adds the token to each HTTP header
config.headers.Authorization = `token The ${store.state.token}`;
}
return config;
},
err = > {
return Promise.reject(err);
});
//HTTP Response interceptor
axios.interceptors.response.use(
response = > {
return response;
},
error = > {
if (error.response) {
switch (error.response.status) {
case 401:
//The 401 clearing token information is displayed and the login page is displayed
store.commit(types.LOGOUT);
router.replace({
path: 'login',
query: {redirect: router.currentRoute.fullPath}}}})return Promise.reject(error.response.data) //Returns an error message returned by the interface
});Copy the code
See/SRC /http.js for the full method.
With these two steps, you can implement login interception on the front end. Logout function is very simple, just need to clear the current token, and then jump to the home page.
About axios
With Axios, many people who are new to Vue find the documentation difficult to understand. That’s what I thought at first. But after a project like this, axios is not hard to understand. It is recommended that you learn Axios more efficiently by looking at documents with the following goals in mind. With these things in mind, you’re basically free to use Axios in your projects.
- A method to initiate an HTTP request
- The data returned when the HTTP request succeeds and its type
- Handling HTTP request failures
- Use of interceptors
- The HTTP configuration
Run and build
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run buildCopy the code