Here to introduce how to use Vue to achieve registration login function

Technology stack:

Vue elment-UI Node.js + Express MongoDB

Prerequisites: Vue-CLI and MongoDB have been installed

The front-end implementation

I. Initialization project:

MacBook-Pro:sign wangyu$ vue init webpack sign
Copy the code

Install vue-Router and ESlint as prompted

Go to the NPM run dev folder. If the welcome page of localhost:8080 is displayed, the initialization is successful

Because we needed element-UI to simplify our page design, we included it. npm install element-ui

Then:

// main.js
import Vue from 'vue'
import Element from 'element-ui'// Load element-ui import VueResource from'vue-resource'
import App from './App'
import router from './router'
import 'element-ui/lib/theme-chalk/index.css'Use (Element) // Use Element vue.use (VueResource) vue.config.productionTip =false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<app/>', components: {App}}) copy the codeCopy the code

Second, write the login page: because the length is not too long (mainly lazy), to login JS code as an example, the rest can be viewed on Github, the truth is similar, not difficult.

<script>
import env from '.. /.. /config/dev.env.js'
let IP = env.SERVER_IP

export default {
  data () {
    return {
      signUpShow: false,
      signInShow: true,
      signInForm,
      signUpForm,
      signUpRule: {
        pass: {validator: validatePass, trigger: 'blur'},
        checkPass: {validator: validateCheckPass, trigger: 'blur'}
      }
    }
  },
  methods: {
    cancel: function () {
      this.$router.push({name: 'mainPage'})
    },
    signIn: function () {
      let data = {
        username: this.signInForm.username,
        password: this.signInForm.pass
      }
      return this.$http.post(IP + '/api/signIn', data, {
        withCredentials: true
      }).then(response => {
        returnResponse.data}). Catch (err => {throw new Error(err.message)})}} </script> Copy codeCopy the code

Note: the above code is not complete, because the verification part of the code has been removed.

1, data () {return {… }} It is easy for beginners to write data as an object, and other rules are functions, please refer to the official website for instructions.

SignIn (); this.$http.post(); First of all, this is the vue-resource functionality, in main.js and loaded, which can be used directly here, and can be understood simply as Ajax. Second, INSTEAD of using callback, I use Promise, which is a feature that was added in ES7 and ES8 (we can use it in the past, but only with a third-party library). 2) Keep the code style simple and avoid noodlelike if else. Get started with javascript Promise

3,

{
    withCredentials: true} Duplicate codeCopy the code

This object is used to tell the browser to take a cookie when sending a POST request, because we need to send the request across domains.

Redirect after the request is sent. Route hops in VUE are as follows: 1.

<router-link :to="{ name: 'user', params: { userId: 123 }}"></router-link> Copy codeCopy the code

2,

this.$router.push({name:"", params:{a: 'aa'}}) copy the codeCopy the code

Params is a parameter. In the target route, you can obtain it in the following way

this.$route.params copies the codeCopy the code

The backend implementation

The logic code is simple: connect to the database, write the business logic, and expose the API. Details see the code, belong to a look to understand the kind of pit is less. The following focuses on the state maintenance of the following background. So Session, Cookie. The difference between the two is simply that a cookie is a real thing. The browser saves the cookie according to the set-cookie field in the header returned by the server and sends the cookie to the server according to the HTTP request packet. Sessions are a way that people have devised to keep track of visitor status, and because HTTP is stateless, you can’t keep track of visitor information, but you do need to keep track of things like user status. A Node session can be implemented using express-session. Note that

const expressSession = require('express-session')
const MongoStore = require('connect-mongo')(expressSession)

app.use(expressSession({name:'blog',store: new MongoStore({mongooseConnection: db.openDB()}), secret:'allen',resave: true, saveUninitialized: true,cookie: ('name'.'value', { path: '/', httpOnly: false,secure: false, maxAge: 50000})})); Copy the codeCopy the code

Session should be used before routing, or, more precisely, before routing the application session, otherwise req.session == undefined, and some static file access can be placed before session as needed.

Paste the main business logic code:

let signUp = function (req, res) {
  detectInfo(req).then(response => {
    const user = new modelUser(response)
    user.save(()=>{
      req.session.user = user
      req.session.save()
      res.jsonp({
        data: user
      })
    }, err => {
      res.status(400).send({
        error: error
      })
    })
  }, error => {
    res.status(400).send({
      error: error.message 
    })
  })
}

let signIn = function (req, res) {
  if(req.session.user) {
    res.status(200).send({
      data: req.session.user
    });
  }else{
    modelUser.find({username: req.body.username, password: req.body.password}).then(data => {
      if(data.length == 0){
        res.status(400).send({
          message: 'User does not exist'})}else{
        req.session.user = data[0]
        req.session.save()
        res.jsonp({
          username: data[0].username
        })
      }
    }, err => {
      res.status(400).send({
        message: err.message
      })
    })
  }
}

let signOut =function (req, res) {
  req.session.user = null
  req.session.save()
  res.status(200).send()
}
Copy the code