preface

Last time we analyzed ruoyi-UI SRC /views/login.vue login page code. This issue is supplemented with further analysis of request and response interception in SRC /utils/request.js, and access restrictions in SRC /permission.js.

Complement of the previous period

watch: {
  $route: {
    handler: function(route) {
      this.redirect = route.query && route.query.redirect;
    },
    immediate: true}},Copy the code

The main purpose of this code is to log in and return to the page before the redirect.

For example, we want to go to the /system/user page. If you do not login, the login page is directly redirected to the link. In this case, use the preceding code to record the redirection location.

this.$router.push({ path: this.redirect || "/" }).catch(() = >{});
Copy the code

After you log in to the system on the login page, switch to the target route. Here is an example of a route:

Request to intercept

Add a token
// Whether to set the token
const isToken = (config.headers || {}).isToken === false
if(getToken() && ! isToken) { config.headers['Authorization'] = 'Bearer ' + getToken() // Allow each request to carry a user-defined token. Change the token based on the actual situation
}
Copy the code

The const isToken is used to determine the state of config.headers. If config.headers. IsToken is set to false, the interceptor does not add the token.

This parameter is not added by default in Ruoyi, so getToken() if the token exists, adds the token to Authorization.

The following is an example of config:

Get request mapping
// get requests to map params parameters
if (config.method === 'get' && config.params) {
  let url = config.url + '? ';
  // Get the params list
  for (const propName of Object.keys(config.params)) {
    const value = config.params[propName];
    var part = encodeURIComponent(propName) + "=";
    if(value ! = =null && typeof(value) ! = ="undefined") {
      // The object type goes to the next level of mapping
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          let params = propName + '[' + key + '] ';
          var subPart = encodeURIComponent(params) + "=";
          url += subPart + encodeURIComponent(value[key]) + "&"; }}else {
        url += part + encodeURIComponent(value) + "&";
      }
    }
  }
  url = url.slice(0, -1);
  config.params = {};
  config.url = url;
}
Copy the code

This section of code maps the various parameter forms to get requests. You can also unify the API definition format under the API folder. Such as:

export function listJobLog(query) {
  return request({
    url: '/monitor/jobLog/list'.method: 'get'.params: query
  })
}
Copy the code

The response to intercept

Response interception is the addition of error code and exception messages. Select a section and analyze it.

if (code === 401) {
  MessageBox.confirm('Login status has expired, you can stay on this page or log in again'.'System info', {
      confirmButtonText: 'Log in again'.cancelButtonText: 'cancel'.type: 'warning'
    }
  ).then(() = > {
    store.dispatch('LogOut').then(() = > {
      location.href = '/index';
    })
  }).catch(() = > {});
Copy the code

This code is a prompt when the login status expires. If you log in again, log out and remove the token in the cookie before switching to /index. You can also cancel it and leave it alone.

access

router.beforeEach((to, from, next) = > {
if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/'})}Copy the code

If the token exists and the target path is login, the system directly switches to /.

Then check whether the user information has been pulled. If no, call the method to obtain the user role table, and then obtain the accessible routing table based on the role. If the role information fails to be obtained, the user logs out and enters the login process again.

const whiteList = ['/login'.'/auth-redirect'.'/bind'.'/register']
/ / not token
if(whiteList.indexOf(to.path) ! = = -1) {
  // Enter the whitelist directly
  next()
} else {
  next(`/login? redirect=${to.fullPath}`) // Otherwise all redirects to the login page
}
Copy the code

If it does not contain the token but is in the sign-on free whitelist, it can also be accessed. Otherwise, redirect to the login page.

other
to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
Copy the code
  • If the page title is not set, the set title method is called
NProgress.configure({ showSpinner: false })
NProgress.start()
NProgress.done()
Copy the code
  • Control the top progress bar

The next plan

  • Analyze the login process of the back-end interface