Login function of Vue cli3+Mongodb+express

My project is Vue Cli3+Electron+Antd+Mongodb+express

Mongodb and Studio 3T are downloaded and installed.Specific can be Google or Baidu.Then start Mongodb

Then open Studio 3T, connect to the database port, right-click to create a new database. The new database I create here is login.

user is your own newly created data collection, roughly as follows:

Set up server

My project is Vue cli 3 + Electron + express. Create a new folder service in the project's root directory, and then create several new folders under it: database, routes, and a server startup file, server.js, as follows

├─ service
│    ├─ database
│    ├─ routes
│    └─ server.js
├─ src
│    ├─ App.vue
│    ├─ assets
│    ├─ background.js
│    ├─ common
│    ├─ components
│    ├─ main.js
│    ├─ router.js
│    ├─ store.js
│    └─ views
└─ vue.config.js

1. Set up a server

Install express:

npm add express -S

Write in the server.js file:

const express = require('express')
const app = express()

// Request header settings, just in case
app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  res.header('Content-Type', 'application/json;charset=utf-8')
  return next()
})
app.get('/', (req, res) => res.send('hello from server'))
app.listen(3000, () => console.log('app listening on port 3000'))

Start the service input node server.js under the service path, and the simple server is successfully set up.

To solve cross-domain problems, you need to include in the vue.config.js file:

devServer: {
    port: 8080,
    proxy: {
      '/user': {
        target: 'http://127.0.0.1:3000',
        changeOrigin: true // Cross-domain
      }
    }
  },

2. Connect to a database

Installation Dependency:

npm add mongodb mongoose -S

Create a new file, db.js, under the database folder, and type:

const mongoose = require('mongoose')
const DBURL = 'mongodb://Localhost:27017/login'//login is the name of the database you created

// Connect to database
mongoose.connect(DBURL)

// Connection Successful
mongoose.connection.on('connected', () => {
  console.log('mongoose connection open to ' + DBURL)
})

// connection failed
mongoose.connection.on('error', error => {
  console.log('Mongoose connection error:' + error)
})

// Disconnect
mongoose.connection.on('disconnected', function () {
  console.log('Mongoose connection disconnected')
})
module.exports = mongoose

Then create a new file, user.js, to create the database Schema, which is the model skeleton of the database collection, or the table structure in the traditional sense of the data attribute model.

/*
 Define a user's Schema
*/
const mongoose = require('./db.js')
const Schema = mongoose.Schema

// Create a model
const UserSchema = new Schema({
  username: String,
  password: String
})

// Export model Module
module.exports = mongoose.model('User', UserSchema)

3. Write interfaces and route modularization

For ease of administration, a routing middleware to express is required.

To facilitate the parsing of data sent by the front end, reference a body-parser middleware and install:

npm add body-parser -S

Then introduce in server.js:

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

Create a new file, user.js, in the routes folder:

const express = require('express')
const router = express.Router()
const User = require('../database/user')

router.post('/login', async (req, res, next) => {
  console.log(req.body)
//Here req.body actually uses the body-parser middleware to parse data sent from the front end
  const username = req.body.username
  const password = req.body.password
  // Determine if the user name and password are the same as the database
  let doc = await User.findOne({ username })
  if (!doc) {
    req.body = {
      code: -1,
      msg: 'user name does not exist'
    }
    res.send(req.body)
  } else if (doc.password !== password) {
    req.body = {
      code: -1,
      msg: 'Password error'
    }
    res.send(req.body)
  } else if (doc.password === password) {
    try {
      req.body = {
        code: 0,
        msg: 'Login Successful',
        username
      }
      res.send(req.body)
    } catch (err) {
      req.body = {
        code: -1,
        msg: 'Login failed, please login again'
      }
      res.send(req.body)
    }
  }
    module.exports = router

Then introduce routes in server.js:

const user = require('./router/user')
app.use('/user', user)

Perfect login function

Install axios:

npm add axios -S

Rewrite axios to Vue's prototype properties:

// main.js
import axios from 'axios'
Vue.prototype.$ajax = axios

Open the SignIn.vue login page and call the interface:

methods: {
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          let loginParams = {
            username: values.userName,
            password: values.password
          }
          this.$ajax.post('/user/login', loginParams).then(res => {
            let result = res.data

            if (result.code === 0) {
              setTimeout(() => {
                this.spinning = true
                const msg = result.msg || 'Login Successful'
                this.$message.success(msg)
                sessionStorage.setItem('user', JSON.stringify(result.username))
                this.$router.push('/')// Go to home page after login
              }, 1000)
              this.spinning = false
            } else {
              const errorMsg = result.errorMsg || 'Logon Failure'
              this.$message.warn(errorMsg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }
  }

Tags: Javascript Mongoose Database Vue axios

Posted on Thu, 07 Nov 2019 22:42:00 -0500 by cirene