Practice of front and back end separation: Realization of access management of Web site foreground based on Vue

Source: Internet
Author: User

JavaScript is a popular language for the moment and is widely used, from the front-end to the back-end, and it is now heavily utilized within our projects to develop front-end pages for CMS systems and other data analysis systems. This person is very interested and as a Hat card extension content to study after school.

JavaScript frameworks are lined up, but the fundamentals are roughly the same, so a tentative attempt is made to choose the vue.js developed by the domestic people. Study Vue.js also more than a week time, talking about the main use of Vue, no outside declarative Rendering, Component System, Client-side Routing, Vue-resource, Axios and depending on the size of the project to decide whether to use the Vuex, learning vue Small, the main transformation of thinking, front-end separation of the component-based web development is really want to practice.

Just my personal site Codesheep recently to develop background management, so just use Vue this set to achieve a bit. When it comes to background management, the problem that is not open is the management of authority. Since you want to practice the front-end separation of this idea, so the background management of all Web front-end things should be independent of the front-end, which includes very important by the front-end to the control of the relevant things according to permissions. What we want to do is: Different permissions for different routes, and the page sidebar should also be based on different permissions, to asynchronously generate the corresponding menu, white is the background management when the user of different permissions to see the interface menu is not the same, so there is a set of procedures for login and authorization here.

# #具体实现
# # #1, click the "Login" button to trigger the login event

this.$store.dispatch(‘LoginByEmail‘, this.loginForm).then(() => {  this.$router.push({ path: ‘/‘ }); //登录成功之后重定向到首页}).catch(err => {  this.$message.error(err); //登录失败提示错误});

The actions of the loginbyemail that are triggered asynchronously are as follows:

LoginByEmail ({ commit }, userInfo) {      const email = userInfo.email.trim()      return new Promise((resolve, reject) => {        loginByEmail(email, userInfo.password).then(response => {          const data = response.data          setToken(response.data.token)          commit(‘SET_TOKEN‘, data.token)          resolve()        }).catch(error => {          reject(error)        })      })    }

It's easy to see what you want to do is put the token (uniquely labeled user) from the server to a local cookie in the browser

# # #2, Global hook Router.beforeeach intercept routes
This step is the core, the specific processing flow is shown as follows:

The specific code is as follows:

router.beforeEach((to, from, next) => {  if (getToken()) {  // 判断是否取到token    if (to.path === ‘/login‘) {      next({ path: ‘/‘ })    } else {      if (store.getters.roles.length === 0) {  // 判断当前用户是否已获取完user_info信息        store.dispatch(‘GetInfo‘).then(res => { // 获取user_info          const roles = res.data.role          store.dispatch(‘GenerateRoutes‘, { roles }).then(() => { // 生成可访问的路由表            router.addRoutes(store.getters.addRouters)  // 动态添加可访问路由表            next({ ...to }) // 放行路由          })        }).catch(() => {          store.dispatch(‘FedLogOut‘).then(() => {            next({ path: ‘/login‘ })          })        })      } else {        next() // 放行该路由      }    }  } else {    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单里的路径,继续让其访问      next()    } else { // 其他不在白名单里的路径全部让其重定向到登录页面!      next(‘/login‘)      alert(‘not in white list, now go to the login page‘)    }  }})

A few important steps in the flowchart explain:

  • Determine if the front end is taking token tokens: GetToken ()

    The operation is very simple, mainly from the cookie, to see if token has been obtained:

    export function getToken () {return Cookies.get(TokenKey)}
  • Vuex Asynchronous Operation Store.dispatch (' GetInfo '): Get user Information

    GetInfo ({ commit, state }) {  return new Promise((resolve, reject) => {    getInfo(state.token).then(response => {      const data = response.data      console.log(data)      commit(‘SET_ROLES‘, data.role)      commit(‘SET_NAME‘, data.name)      resolve(response)    }).catch(error => {      reject(error)    })  })}

    The operation is also simple, using a Get RESTful API to get the user's role and name from the server

  • Vuex Asynchronous Operation Store.dispatch (' Generateroutes ', {roles}): Generate different foreground routes based on different roles
    GenerateRoutes ({ commit }, data) {  return new Promise(resolve => {    const { roles } = data    let accessedRouters    if (roles.indexOf(‘admin‘) >= 0) {      accessedRouters = asyncRouter    } else {      accessedRouters = filterAsyncRouter(asyncRouter, roles)    }    commit(‘SET_ROUTERS‘, accessedRouters)    resolve()  })}

    As can be seen from the code, I have only distinguished between admin roles admin and other ordinary users (that is, non-aadmin two permissions)

The series of practical follow-up will also try more, will be written, I am a beginner, the road is long and quest ...

Postscript

Author of more original articles in this

Practice of front and back end separation: Realization of access management of Web site foreground based on Vue

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.