登录前端页面

vue-element已经集成了登录功能,我们这边只需要将前端和后端的接口打通即可

登录流程

通过当前代码分析:

  1. 访问view/login/index.vue的登录页面,输入用户名/密码点击登录
  2. 调用store/modules/user.js中的接口,处理业务逻辑
  3. 调用api/user.js中的请求,和后端通信

接下来就是按需修改代码就可以了:

首先配置全局后端路由接口,把mock数据接口屏蔽,并根据上次配置的后端api服务(localhost:8888),在vue.config.js中修改如下:

  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // 路由的前缀地址
      'auth': {
        target: 'http://localhost:8888', // 后端api接口的地址
        changeOrigin: true
      }
    }
    //屏蔽该部分 before: require('./mock/mock-server.js') 
  },

在view/login/index.vue中handlerLogin修改代码,根据后端修改如下:

tips:注意我这里将loginForm的参数值更改了,除了以下的内容,其他相关的loginForm也要相应的变更,不然会报错

  handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 全局配置中已经添加auth前缀,所以只需要写后面即可
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch((err) => {
              console.log(err)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

修改store/modules/user.js中的内容如下:

  // user login
  login({ commit }, userInfo) {
    const { user_name, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ user_name: user_name.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.Token)
        setToken(data.Token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        // todo 由于后台数据返回的数据数据不完整,暂时先将一些需要的数据进行初始化,后期进行优化
        const dataNew = {
          roles: ['root'],
          introduction: 'I am a super administrator',
          avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
          name: data['username']
        }
        const { roles, name, avatar, introduction } = dataNew
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // 保存用户信息
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(dataNew)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 删除用户信息
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

修改api/user.js中的内容如下:

export function login(data) {
  return request({
    url: '/user/login',
    method: 'post',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8'
    },
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
  })
}

全局添加鉴权请求,修改src/utils/request.js中的内容如下:

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // 后端鉴权的header名是Authorization
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 鉴权失败验证
error => {
    console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // token失效,跳转登录
    if (error.response.status === 401) {
      store.dispatch('user/resetToken').then(() => {
        location.reload()
      })
    } else if (error.response.status === 406) {
      Message({
        message: '无权限',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
  }

修改完成之后,启动前端服务:

npm run dev

效果如下:
登录