Koa & mongoose & Vue to separate front end and back end — 06 front end login & Registration

Time:2020-9-14

Last section review

  • Analysis of load
  • Server Registration & login logic
  • Storage & Query of database

job content

  • Initialize front end environment
  • Create front end route
  • axiosRequest interface

preparation

  • Global installation depends on / / to initialize the project through Vue / cli

├── @vue/[email protected]

├── @vue/[email protected]

  • vue init webpack .///Switch to/clientUnder the table of contents

Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

  • npm i -S axios//Switch to/clientUnder the table of contents

Page logic

  • npm run startCheck whether the page can be accessed normallylocalhost:8080

Technology selection

Own project, no special requirements, choose what you are familiar withelement-uiUI libraryscssPrecompiled language quickly builds the page.

Initialization page

//Update file / client / SRC/ App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>
//Update file / client / SRC / router/ index.js
//Delete file by the way / 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
    }
  ]
})
//New file / client / SRC / views / login/ index.vue
<template>
  <div>
    Login
  </div>
</template>

Display effect / / if the update is not timely, you can restart the front-end service
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

introduceelement-uiandscss

  • Installation dependency:npm i -S element-ui node-scss [email protected]//Sass loader installation 7Version, current version 8Compilation failed
  • Complete introduction of element
//Update file / 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/>'
})
  • Test usability
//Update file / client / SRC / views / login/ index.vue
<template>
  <div>
    <el-button type="primary">Login</el-button>
    < p class = "red" > this is SCSS</p>
  </div>
</template>
<style lang="scss" scoped>
$color: red;
.red {
  color: $color;
}
</style>
  • test result

Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

Quickly build page

In order to save time, you can directlyElementOfficial website > component > form form, copy an example with verification

//Update file / 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 = account number "prop =" account ">
        <el-input v-model=" form.account "Placeholder = please output account" > < / El input > "
      </el-form-item>
      < El form item label = password "prop = password" >
        <el-input type="password" v-model=" form.password "Placeholder = please output password" > < / El input >
      </el-form-item>
      <el-form-item>
        < El button type = "primary" @ Click = "onlogin" > log in < / El button >
        < El button type = "primary" @ Click = "onregister > < El button > registration
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      formName: 'LoginForm',
      form: {
        account: '',
        password: ''
      },
      rules: {
        account: [
          {required: true, message: 'please enter account number', trigger: 'blur'},
          {Min: 5, message: 'at least 5 characters in length', trigger: 'blur'}
        ],
        password: [
          {required: true, message: 'please enter password', trigger: 'blur'},
          {Min: 3, message: 'at least 3 characters in length', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    async onLogin () {
      console.log('login')
    },
    async onRegister () {
      console.log('register')
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
//New file: client / SRC / views / login/ index.scss
.form-login {
  width: 600px;
  margin: 0 auto;
}
  • Page display

Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

Add HTTP request

At the time of preparation, thenpm i -S axiosinstallaxios

//New configuration file: client / SRC / config/ http.js
export const BASE_URL = 'http://localhost:3000/'
export const TIMEOUT = 15000
//New Axios instance file: 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 // the request response with status code > = 200 can be intercepted
  }
})

export default instance

Note: Axios only returns HTTP code by default2**Response to request

Testing HTTP requests

//Update file: server / control/ users.js
async function list (ctx) {
  try {
    const users = await  userModel.find (); // find all users
    ctx.body = {
      code: '200',
      data: users,
      MSG: 'query succeeded'
    }
  } catch (err) {
    ctx.body = {
      code: '403',
      data: null,
      msg: err.message
    }
  }
}
//Update file: 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>
...
  • Effect display

Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration
Cross domain request occurs. Here we switch to/server/Directory, install dependenciesnpm i -S koa2-cors(online, it can be usednginxActing as an agent)

//Update file: 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());
...

Restart the back-end service, and then clickhttp://localhost:8080/#/loginSee the result of the request
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

Filter return results

As can be seen from the return interface, when the request server succeeds, it only needs tores.dataYou can useinstance.interceptorsFilter the returned data.

//Update file: 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

Request results
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

Login logic

//Update file: 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 is not used$ message.error ('')
              type: 'error',
              message: res.msg
            })
          }
        }
      } catch (err) {
        console.error(err)
      }
    },
...
  • this.$message({})Instead of usingthis.$message.error()Because if res does not return, it will reportElementThe error of the information misleading.

Update the routing file so that the login successfully jumps toHomeassembly

//Update routing file:
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
    }
  ]
})
//New file: client / SRC / views / home/ index.vue
<template>
  <div>Home</div>
</template>

Use the previous section to pass thePostmanCreatedadminAccount login and result display
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration
The slow motion diagram is as follows:
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration

Registration logic

//Update file: 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: 'registered successfully'
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        }
      } catch (err) {
        console.error(err)
      }
    }
...

Test failure results
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration
Test success results
Koa & mongoose & Vue to separate front end and back end -- 06 front end login & Registration
You can use the newly created account to log in. If you find that you can successfully / view the database, whether you have successfully added new users

Reference documents

element-ui
vue-router
axios

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]