Vue + axios implements the login interception instance code, vueaxios

Source: Internet
Author: User

Vue + axios implements the login interception instance code, vueaxios

A project learns to use the vue bucket + axios to log on, intercept, and log out, and use the http interceptor of axios to intercept requests and responses.

Preface

This project uses the personal token provided by Github as the logon token to access your Repository List through the token. This project is used to learn how to implement the interception of logon and interception, logout, and token failure required by a front-end project and the use of the corresponding axios interceptor.

Prepare your Github Personal Token (generate Token ). After the Token is generated, access the Demo to view your Repository List.

Project Structure

. ── README. md ├ ── dist // package the constructed folder │ ├ ── build. js │ ── build. js. map ── index.html ── package. json ├ ── src │ ├ ── App. vue │ ── assets │ ├ ── css.css │ ├ ── icon.css │ ── logo.png │ ── constant │ ── api. js // configure the api interface file │ ── http. js // encapsulate the configuration file │ ── index for fetch, post request, and http interceptor. vue │ ── login. vue │ ── main. js │ ├ ── repository. vue │ ── router. js // route configuration file │ ── store │ ├ ── store. js │ ── types. js // vuex types ── webpack. config. js

Technology Stack

  1. Vue 2.0
  2. Vue-router
  3. Vuex
  4. Axios
  5. Vue-material

Logon interception Logic

Step 1: Route Interception

First, you need to add another Custom Field requireAuth when defining the route to determine whether the access to the route needs to be logged on. If the user has logged on, the route entry is successful. Otherwise, the logon page is displayed.

Const routes = [{path: '/', name: '/', component: Index}, {path: '/repository', name: 'repository ', meta: {requireAuth: true, // Add this field, indicating that you need to log on to the route}, component: Repository}, {path: '/login', name: 'login ', component: Login}];

After the route is defined, we mainly use the hook function beforeEach () provided by vue-router to judge the route.

Router. beforeEach (to, from, next) => {if (. meta. requireAuth) {// determine whether the route requires the logon permission if (store. state. token) {// obtain whether the current token exists next () through vuex state;} else {next ({path: '/login', query: {redirect:. fullPath} // use the redirected route path as the parameter. After Successful Logon, the route will jump to this route.} else {next ();}})

Each Hook method receives three parameters:

  1. To: Route: Target Route object to be entered
  2. From: Route: the Route from which the current navigation is about to exit
  3. Next: Function: You must call this method to resolve the hook. The execution result depends on the call parameters of the next method.
    1. Next (): Perform the next hook in the pipeline. If all the hooks are finished, the navigation status is confirmed (confirmed ).
    2. Next (false): interrupt the current navigation. If the URL of the browser changes (either manually or backward), the URL address is reset to the address corresponding to the from route.
    3. Next ('/') or next ({path: '/'}): jump to a different address. The current navigation is interrupted and a new navigation is performed.

Make sure you want to call the next method, otherwise the hook will not be resolved.

For the complete method, see/src/router. js.

Here, to. meta contains our custom data, which includes the requireAuth field we just defined. This field is used to determine whether the route requires logon permissions. If necessary, if the current application does not have a token, the logon page is displayed. Log on to the target route.

Will the interception end now? No. This method is only a simple front-end route control and does not really prevent users from accessing the route that requires logon permissions. Another case is that the current token is invalid, but the token is still saved locally. At this time, when you access a route that requires logon permissions, you should actually have the user log on again. At this time, you need to combine the http status code returned by the http interceptor + backend interface to determine.

Step 2: Interceptor

To process all http requests and responses in a unified manner, you must use the axios interceptor. By configuring http response inteceptor, when the backend interface returns 401 Unauthorized (Unauthorized), the user can log on again.

// Http request interceptor axios. interceptors. request. use (config => {if (store. state. token) {// determine whether a token exists. If yes, the token config is added to each http header. 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 to clear the token information and jump to the logon page store. commit (types. LOGOUT); router. replace ({path: 'login', query: {redirect: router. currentRoute. fullPath }}} return Promise. reject (error. response. data) // return the error message returned by the interface });

For the complete method, see/src/http. js.

Through the above two steps, you can implement login interception at the front end. The logout function is simple. You only need to clear the current token and then jump to the homepage.

About axios

For axios, many people who have just started learning vue find it hard to understand the documentation. I thought so at the beginning. However, after such a project, axios is hard to understand. It is recommended that you take the following purpose to view the document when learning axios, which will be more efficient. After mastering the following content, you can use axios in the project without any difficulty.

  1. Method for initiating an http request
  2. Data returned when an http request is successful and its type
  3. Handling of http request failures
  4. Use of interceptor
  5. Http configuration

Axios documentation

Operation and Construction

# install dependenciesnpm install# serve with hot reload at localhost:8080npm run dev# build for production with minificationnpm run build

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.