Koa & Mongoose & Vue实现先后端分离--06前端登陆&注册

上节回顾

  • 荷载的解析
  • 服务端注册&登陆逻辑
  • 数据库的存储 & 查询

工做内容

  • 初始化前端环境
  • 建立前端路由
  • axios请求接口

准备工做

  • 全局安装依赖 // 以便经过vue/cli初始化项目

├── @vue/cli@4.1.2css

├── @vue/cli-init@4.1.2前端

  • vue init webpack ./ // 先切换到/client目录下

回答初始化问题

  • npm i -S axios // 先切换到/client目录下

页面逻辑

  • npm run start查看页面是否能正常访问localhost:8080

技术选型

本身的项目,没特殊要求,选择本身熟悉的element-uiUI库、scss预编译语言快速搭建页面。vue

初始化页面

// 更新文件:/client/src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>
// 更新文件:/client/src/router/index.js
// 顺便删除文件:/client/src/components/Helloworld.vue
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }
  ]
})
// 新建文件: /client/src/views/login/index.vue
<template>
  <div>
    Login
  </div>
</template>

展现效果 //更新不及时,能够重启前端服务
Loginnode

引入element-uiscss

  • 安装依赖:npm i -S element-ui node-scss sass-loader@7 // sass-loader安装7.版本,目前最新版8.编译失败
  • 完整引入Element
// 更新文件:/client/src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'

Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
  • 测试可用性
// 更新文件:/client/src/views/login/index.vue
<template>
  <div>
    <el-button type="primary">Login</el-button>
    <p class="red">这是scss</p>
  </div>
</template>
<style lang="scss" scoped>
$color: red;
.red {
  color: $color;
}
</style>
  • 测试结果

Element

快速搭建页面

为了省事,直接从Element官网 > 组件 > Form表单,拷贝一份带校验的示例改改webpack

// 更新文件:/client/src/views/login/index.vue
<template>
  <div class="page-login">
    <el-form :ref="formName" class="form-login" :model="form" :rules="rules">
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输出账号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输出密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin">登录</el-button>
        <el-button type="primary" @click="onRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      formName: 'LoginForm',
      form: {
        account: '',
        password: ''
      },
      rules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 5, message: '长度至少5个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, message: '长度至少3个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onLogin () {
      console.log('login')
    },
    async onRegister () {
      console.log('register')
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
// 新建文件:client/src/views/login/index.scss
.form-login {
  width: 600px;
  margin: 0 auto;
}
  • 页面展现

Login页面展现

添加http请求

在准备工做时,已经npm i -S axios安装axiosios

// 新建配置文件:client/src/config/http.js
export const BASE_URL = 'http://localhost:3000/'
export const TIMEOUT = 15000
// 新建axios实例文件:client/src/utils/http.js
import axios from 'axios'
import { BASE_URL, TIMEOUT } from '@/config/http'

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
  validateStatus: function (status) {
    // return status >= 200 && status < 300; // default
    return status >= 200 // 可拦截状态码>=200的请求响应
  }
})

export default instance

注意:axios默认只返回Http Code为2**请求的响应nginx

测试Http请求

//更新文件:server/control/users.js
async function list (ctx) {
  try {
    const users = await userModel.find(); //查出所有用户
    ctx.body = {
      code: '200',
      data: users,
      msg: '查询成功'
    }
  } catch (err) {
    ctx.body = {
      code: '403',
      data: null,
      msg: err.message
    }
  }
}
//更新文件:client/src/views/login/index.vue
...
<script>
import http from '@/utils/http'
...
  methods: {
    async onLogin () {
      console.log('register')
    },
    async onRegister () {
      console.log('register')
    }
  },
  async created () {
    const res = await http.get('/users')
    console.log(res)
  }
...
</script>
...
  • 效果展现

cors
发生跨域请求,这里咱们切换到/server/目录下,安装依赖npm i -S koa2-cors(线上的话,可使用nginx作代理)git

// 更新文件:server/app.js
const koa = require('koa');
const bodyParser = require('koa-body');
const cors = require('koa2-cors');

const routes = require('./router');

const app = new koa();
app.use(cors());
...

重启后端服务,便可在页面http://localhost:8080/#/login看到请求结果
users请求github

过滤返回结果

从返回接口能够看出,请求服务端成功时,只须要res.data便可,使用instance.interceptors对返回数据进行过滤。web

// 更新文件:client/src/utils/http.js
...
// Add a response interceptor
instance.interceptors.response.use(
  async res => {
    if (/^20./.test(res.status)) {
      return res.data
    }
    console.log('------response=======', res)
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

export default instance

请求结果
interceptor

登陆逻辑

//更新文件:client/src/views/login/index.vue
...
    async onLogin () {
      try {
        const valid = await this.$refs[this.formName].validate()
        if (valid) {
          const { account, password } = this.form
          const res = await http.post(
            '/users?action=login',
            {
              account,
              password,
            }
          )
          console.log(res)
          if (res && res.code === '200') {
            this.$router.replace('/home')
          } else {
            this.$message({ // 没有使用this.$message.error('')
              type: 'error',
              message: res.msg
            })
          }
        }
      } catch (err) {
        console.error(err)
      }
    },
...
  • this.$message({}),而没有使用this.$message.error(),由于发现若是res没有返回的话,会报Element的错误,形成信息误导。

更新路由文件,使登陆成功跳转到Home组件

// 更新路由文件:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login'
import Home from '@/views/home'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/home',
      name: 'home',
      component: Home
    }
  ]
})
// 新建文件:client/src/views/home/index.vue
<template>
  <div>Home</div>
</template>

使用上节经过Postman建立的admin帐户登陆,结果展现
admin登陆
缓慢的动图以下:
login.gif

注册逻辑

//更新文件:client/src/views/login/index.vue
...
    async onRegister () {
      try {
        const valid = await this.$refs[this.formName].validate()
        if (valid) {
          const { account, password } = this.form
          const res = await http.post(
            '/users?action=register',
            {
              account,
              password
            }
          )
          if (res.code === '200') {
            this.$refs[this.formName].resetFields()
            this.$message({
              type: 'success',
              message: '注册成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        }
      } catch (err) {
        console.error(err)
      }
    }
...

测试失败结果
失败
测试成功结果
成功
可使用新建立的账号登陆,发现能够成功/查看数据库,是否成功新增用户

参考文档

element-ui
vue-router
axios

相关文章
相关标签/搜索