In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to achieve login interception in vue+axios". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to achieve login interception in vue+axios" can help you solve the problem.
The project uses the personal token provided by Github as the login token to access your Repository List through token. Through this project, learn how to implement login and interception, logout, token failure interception and the use of corresponding axios interceptors needed in a front-end project.
To prepare, you need to generate your own Github Personal Token (generate Token) first. After Token is generated, visit Demo to view your Repository List.
Project structure
. ├── README.md ├── dist / / packaged and constructed folder │ ├── build.js │ └── build.js.map ├── index.html ├── package.json ├── src │ ├── App.vue │ ├── assets │ │ ├── css.css │ │ ├── icon.css logo.png constant / / Configure api interface file │ ├── http.js / / encapsulate fetch, Post request and http interceptor profile │ ├── index.vue │ ├── login.vue │ ├── main.js │ ├── repository.vue │ ├── router.js / / routing profile │ └── store │ ├── store.js │ └── types.js / / vuex types └── webpack.config.js
Technology stack
Vue 2.0
Vue-router
Vuex
Axios
Vue-material
Login intercept logic
Step 1: route interception
First of all, when defining a route, you need to add an additional custom field, requireAuth, to determine whether login is required for the access to the route. If the user is already logged in, he can successfully enter the route, otherwise he or she will enter the login page.
Const routes = [{path:'/', name:'/', component: Index}, {path:'/ repository', name: 'repository', meta: {requireAuth: true, / / add this field to indicate that you need to log in to enter this route}, component: Repository}, {path:' / login', name: 'login', component: Login}]
After defining the route, we mainly use the hook function beforeEach () provided by vue-router to judge the route.
Router.beforeEach ((to, from, next) = > {if (to.meta.requireAuth) {/ / determine whether the route requires login permission if (store.state.token) {/ / get whether the current token exists next () through vuex state } else {next ({path:'/ login', query: {redirect: to.fullPath} / / take the redirected route path as a parameter, and jump to this route} after a successful login)}} else {next ();}})
Each hook method receives three parameters:
To: Route: the destination routing object to be entered
From: Route: the route from which the current navigation is leaving
Next: Function: be sure to call this method to resolve the hook. The execution effect depends on the calling parameters of the next method.
Next (): proceed to the next hook in the pipe. If all the hooks are finished, the navigation status is confirmed (confirmed).
Next (false): interrupts the current navigation. If the URL of the browser changes (either manually by the user or by the browser back button), the URL address is reset to the address of the from route.
Next ('/') or next ({path:'/'}): jump to a different address. The current navigation is interrupted and a new navigation is carried out.
Be sure to call the next method, otherwise the hook will not be resolved.
For a complete method, see / src/router.js
Among them, to.meta is our custom data, including the requireAuth field we just defined. Use this field to determine whether the route requires login permissions. If necessary, and there is no token in the current application, jump to the login page and log in. Jump to the destination route after a successful login.
Is the login intercept over here? No. This approach is only a simple front-end routing control and does not really prevent users from accessing routes that require login privileges. There is also a situation where the current token is invalid, but the token is still saved locally. When you go to access a route that requires login permissions, you should actually ask the user to log in again. At this point, it needs to be judged by combining the http status code returned by the http interceptor + back-end interface.
Step 2: interceptor
To handle all http requests and responses uniformly, you need to use axios's interceptor. By configuring http response inteceptor, when the back-end interface returns 401 Unauthorized (unauthorized), let the user log in again.
/ / http request interceptor axios.interceptors.request.use (config = > {if (store.state.token) {/ / determine whether token exists, and if so, each http header adds token config.headers.Authorization = `token ${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: / return 401 clear token information and jump to login page store.commit (types.LOGOUT) Router.replace ({path: 'login', query: {redirect: router.currentRoute.fullPath}})} return Promise.reject (error.response.data) / / returns the error message returned by the API})
For a complete method, see / src/http.js.
With these two steps above, login interception can be implemented at the front end. The logout function is very simple, just clear the current token, and then jump to the home page.
About axios
For axios, many people who are just beginning to learn vue find the document more difficult to understand. That's what I thought at first. But after coming down through such a project, I found that axios is not difficult to understand. It is recommended that it is more efficient to read the documentation with the following purpose when learning axios. Because you have mastered the following, you can basically use axios in your project without barriers.
The method to initiate a http request
The data returned when the http request is successful and its type
Failed processing of http request
The use of interceptors
Configuration of http
Axios document
Operation and construction
# install dependenciesnpm install# serve with hot reload at localhost:8080npm run dev# build for production with minificationnpm run build's content on "how to intercept login with vue+axios" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.