vue2+element UI+axios+sqlite connect to local database

Posted by bigwatercar on Tue, 01 Feb 2022 01:14:23 +0100

Problem Description:

Now there is a front-end project of vue2+element UI. It is easy to build a database with sqlite, but how to connect them with js?

First, npm install sqlite ~ search a lot on the Internet.

  • Found an open source project using Vue js + Element UI + Express + axios + SQLite3. Compare it with my project:
    https://github.com/shawvey/The-Weather-Helper If github cannot log on, you can git clone https://gitee.com/liu-qiuqi/The-Weather-Helper.git
    (o ▽ o ☆ here This is from gitee.


    My project directory:

    Weather helper app vue and main js corresponds to vue and js in each folder of pages in my project
    main.js:
import Vue from 'vue';
import App from './App';
import router from './router';//ignore
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-default/index.css';    // Default theme
import SIdentify from './components/page/Identify';    //Custom components
import "babel-polyfill";
import axios from 'axios';
Vue.use(axios);
Vue.component("SIdentify",SIdentify);
Vue.use(ElementUI);
Vue.use(axios);

new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

App.vue

<template>
    <div id="app">
        <router-view></router-view>
    </div>
</template>
<style>
    @import "../static/css/main.css";
    @import "../static/css/color-dark.css";    
</style>

/components/page/Login.vue

<template>
    <div class="login-wrap">
        <div class="ms-title">Login</div>
        <div class="ms-login">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
                <div v-if="errorInfo">
                    <span>{{errInfo}}</span>
                </div>
                <el-form-item prop="name">
                    <el-input v-model="ruleForm.name" placeholder="Username" ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" placeholder="Password" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
                </el-form-item>
                <el-form-item  prop="validate">
                    <el-input v-model="ruleForm.validate" class="validate-code" placeholder="" ></el-input>
                    <div class="code" @click="refreshCode">
                        <s-identify :identifyCode="identifyCode"></s-identify>
                    </div>
                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')">Submit</el-button>
                </div>
                <p class="register" @click="handleCommand()">Create an Account</p>
            </el-form>
        </div>
    </div>    
</template>

<script>
import axios from 'axios';
    export default {
        name: 'login',
        data() {
            return {
                identifyCodes: "1234567890",
                identifyCode: "",
                errorInfo : false,
                ruleForm: {
                    name: '',
                    password: '',
                    validate: ''                    
                },
                rules: {
                    name: [
                        { required: true, message: 'please enter username', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: 'please enter password', trigger: 'blur' }
                    ],
                    validate: [
                        { required: true, message: 'please enter verification code', trigger: 'blur' }
                    ]
                }
            }
        },
        mounted() {
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        methods: {
            submitForm(formName) {
                // debounceAjax(formName)
                const self = this;
                self.$refs[formName].validate((valid) => {
                    if (self.ruleForm.validate != this.identifyCode){
                        alert('Please enter true verification code!')
                    }
                    else if (self.ruleForm.validate== this.identifyCode) {    
//Send request to backend / api/user/login                
                        axios.post('/api/user/login',JSON.stringify(self.ruleForm))
                        .then((response) => {
                            console.log(response);
                            if (response.data == -1) {
                                self.errorInfo = true;
                                self.errInfo = 'no such user';
                                console.log('Invalid username or password.')
                            } else if (response.data == 0) {
                                console.log('Invalid username or password.')
                                self.errorInfo = true;
                                self.errInfo = 'Invalid username or password.';
                            } else if (response.status == 200) {
                                sessionStorage.setItem('ms_userId',self.ruleForm.name);
                                sessionStorage.setItem('ms_username',self.ruleForm.name);
                                sessionStorage.setItem('ms_user',JSON.stringify(self.ruleForm));
                                self.$router.push('/readme');
                                console.log(JSON.stringify(self.ruleForm)); 
                            }                            
                        }).then((error) => {
                            console.log(error);
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleCommand() {
                this.$router.push('/register');
            },
            randomNum(min, max) {
                return Math.floor(Math.random() * (max - min) + min);
            },
            refreshCode() {
                this.identifyCode = "";
                this.makeCode(this.identifyCodes, 4);
            },
            makeCode(o, l) {
                for (let i = 0; i < l; i++) {
                    this.identifyCode += this.identifyCodes[
                    this.randomNum(0, this.identifyCodes.length)
                    ];
                }
            }
        }
    }
</script>

In the service folder

app.js

//Reference userapi. In api folder js
const userApi = require('./api/userApi');//important
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded())

app.use('/api/user', userApi);//important
//The front-end sending path of '/ api/user', such as' / api/user / Login 'in the front, is in/ api/userApi. A method in JS is as follows

app.listen(3000);
console.log('success listen at port: 3000')

userApi.js

var express = require('express');
var router = express.Router();
var $sql = require('../db/sqlMap');
const sqlite3 = require('sqlite3').verbose();

var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.send(ret);
    }
}

var dateStr = function(str) {
    return new Date(str.slice(0,7));
}
//search user
router.post('/login', (req, res) => {
    let db = new sqlite3.Database('./db/DB.db', (err) => {
    if (err) {
        console.error(err.message);
    }
        console.log('Connected to the database.');
    });
    var sql_name = $sql.user.select_name;
    var params = req.body;
    var keywords = JSON.parse(Object.keys(params));
    console.log(keywords);
    if (keywords.name) {
        sql_name += "where username ='"+ keywords.name +"'";
    }
    db.get(sql_name, function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result === undefined) {
            res.send('-1')   //cannot search username,return -1
        } else {
            if(result.password === keywords.password) {
                jsonWrite(res, result);
            } else {
                res.send('0')  //username
            }
        }
    })
    db.close();
});
module.exports = router;

Because the configuration of Weather consists of config, build and package JSON is set together, but my project only has Vue config. JS and package JSON, so after comparison, I will Vue config. JS changed to this:

let pageMethod = require('./src/util/getPages.js');
let pages = {}
pages = pageMethod.pages();
module.exports = {

  pluginOptions: {
    webpack: {
      dir: [
        './webpack'
      ]
    }
  },
  lintOnSave: false, //Disable eslint
  productionSourceMap: false,
  // eslint-disable-next-line no-undef
  pages,
  devServer: {
    index: 'Login.html', //By default, start serve to open page1 page
    open: process.platform === 'darwin',
    host: '',
    port: 8080,
    https: false,
    hotOnly: false,
//extension
    proxyTable: {
      '/api':{
          // target:'http://jsonplaceholder.typicode.com',
          target: 'http://127.0.0.1:3000/api/',
          changeOrigin:true,
          pathRewrite:{
              '^/api':''
          }
      }
  },
    }
  }

After drawing the gourd according to the above picture - it was found that it was not connected 😓

There should be a problem with the configuration file. How to configure "what address does the front end send requests to"?

I found a blog about Vue config. The difference between JS (mine) and webpack (configuration file of the way used by weather helper): here 👀
If you find nothing wrong, you just use proxy. The above is not changed. Write proxy as proxyTable. Damn it 🤢, The correct is as follows:

let pageMethod = require('./src/util/getPages.js');
let pages = {}
pages = pageMethod.pages();
module.exports = {

  pluginOptions: {
    webpack: {
      dir: [
        './webpack'
      ]
    }
  },
  lintOnSave: false, //Disable eslint
  productionSourceMap: false,
  // eslint-disable-next-line no-undef
  pages,
  devServer: {
    index: 'Login.html', //By default, start serve to open page1 page
    open: process.platform === 'darwin',
    host: '',
    port: 8080,
    https: false,
    hotOnly: false,
//extension
    proxy: {
      '/api':{
          // target:'http://jsonplaceholder.typicode.com',
          target: 'http://127.0.0.1:3000/api/',
          changeOrigin:true,
          pathRewrite:{
              '^/api':''
          }
      }
  },
    }
  }

There is another problem ~ tired heart: error status:500 is reported after starting the project. It is found that the data transmitted to the back end is long as follows: (req.body) syntax error: unexpected end of JSON input at JSON is displayed in terminal parse ()

req.body:
{ '{"account":"001","password":"123456","checked":': [ '' ] }

Solution:

User login is simply realized. Generally speaking, the back-end is configured as follows:

  • Step 1: copy the service folder in the weather helper to the project root directory (src directory), and use the database management tool (SqliteAdministrator can be downloaded from here, link: https://pan.baidu.com/s/1GwrPq9RBt4Rre2SzV-wlUg Extraction code: 7wll) create a new database User table. Save the database file with suffix s3db in / service/db.
  • Step 2: modify / service / APP js
const userApi = require('./api/userApi');//Change to your own API relative path
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded())

app.use('/api/user', userApi);//Change to the corresponding 'front end sending request address', corresponding to the variable name

app.listen(3000);
console.log('success listen at port: 3000')
var sqlMap = {
   user: {
       add: 'INSERT INTO User [(account, password, portrait,realname,phone)]  VALUES',
       select_account: 'SELECT * FROM User', 
       update_user: 'UPDATE User SET'
   }
}

module.exports = sqlMap;
  • Step 4: create / modify / service / API / xxapi js
    I changed userApi to this
var express = require('express');
var router = express.Router();
var $sql = require('../db/sqlMap');
const sqlite3 = require('sqlite3').verbose();



var jsonWrite = function(res, ret) {
    if(typeof ret === 'undefined') {
        res.send('err');
    } else {
        console.log(ret);
        res.send(ret);
    }
}

var dateStr = function(str) {
    return new Date(str.slice(0,7));
}

//search user
//User login attempted
router.post('/login', (req, res) => {
    let db = new sqlite3.Database('./db/IIs.s3db', (err) => {//Write your own database file name in single quotation marks
    if (err) {
        console.error("!!!!")
        console.error(err.message);
    }
        console.log('Connected to the database.');
    });
    var sql_account = $sql.user.select_account;
    var params = req.body;
    var keywords = JSON.parse(Object.keys(params));
    console.log(keywords);
    if (keywords.account) {
        sql_account += " where account ='"+ keywords.account +"'";
    }
    db.get(sql_account, function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result === undefined) {
            res.send('-1')   //cannot search username,return -1
        } else {
            if(result.password === keywords.password) {
                jsonWrite(res, result);
            } else {
                res.send('0')  //username
            }
        }
    })
    db.close();
});


module.exports = router;

  • Step 5: modify Vue. Exe under the root directory config. JS file, if not, create one( 👀 Reference here):
let pageMethod = require('./src/util/getPages.js');
let pages = {}
pages = pageMethod.pages();
module.exports = {

  pluginOptions: {
    webpack: {
      dir: [
        './webpack'
      ]
    }
  },
  lintOnSave: false, //Disable eslint
  productionSourceMap: false,
  // eslint-disable-next-line no-undef
  pages,
  devServer: {
    index: 'Login.html', //By default, start serve to open page1 page
    open: process.platform === 'darwin',
    host: '',
    port: 8080,
    https: false,
    hotOnly: false,
    //Add the following proxy to devServer
    proxy: {
      '/api':{
          // target:'http://jsonplaceholder.typicode.com',
          target: 'http://localhost:3000/api/',
          changeOrigin:true,
          pathRewrite:{
              '^/api':''
          }
      }
  },
    }
  }

If the project directory is similar to weather helper, the configuration file can refer to it directly!

  • In / SRC / pages / login / login Vue:
<template>
  <div id="login">
    <div class="login-box">
      <div id="normalLoginTab" class="loginForm" style="display: block">
        <h2 class="loginbox-title">Account login</h2>
        <div class="loginUrs" style="height: 302px">
          <div class="g-bd">
            <!-- Login form -->
            <el-form
              ref="Loginform"
              :model="user"
              style="width: 70%; margin: auto"
            >
              <el-form-item>
                <el-input v-model="user.account" placeholder="Please enter the account number" style="height: 40px; line-height: 40px;" />
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="user.password"
                  placeholder="Please input a password"
                  show-password
                />
              </el-form-item>
              <el-form-item style="margin-top: -20px">
                <el-checkbox v-model="checked" type="check"
                  >Remember the password</el-checkbox
                >
                <router-link
                  to="/"
                  style="
                    margin-left: 175px;
                    text-decoration: none;
                    color: #42a5eb;
                  "
                  >Forget the password?</router-link
                >
              </el-form-item>
              <el-form-item style="margin-top: -30px">
                <el-button type="goon" @click="doLogin()"
                  >Ascend&nbsp;&nbsp;enter</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    
  </div>
</template>

<script>
import qs from "qs";
import axios from "axios";
export default {
  data() {
    return {
      user: {
        account: "",
        password: "",
        portrait:"",
        realname:"",
        phone:""
      },
      checked: [],
      errorInfo : false,
      errInfo:"",
      rules: {
        account: [
            { required: true, message: 'please enter username', trigger: 'blur' }
        ],
        password: [
            { required: true, message: 'please enter password', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    doLogin() {
      // debounceAjax(formName)
      const self = this;
      if (!self.user.account){
          alert('Please enter an account!')
      }
      else if(!self.user.password){
          alert('Please enter a password!')
      }
      else if(self.user.password&&self.user.account){      
          var dataa={account:this.user.account,password:this.user.password}   
          axios.post('/api/user/login',JSON.stringify(dataa))
          .then((response) => {
              if (response.data == -1) {
                  self.errorInfo = true;
                  self.errInfo = 'no such user';
                  console.log('Invalid username or password.')
              } else if (response.data == 0) {
                  console.log('Invalid username or password.')
                  self.errorInfo = true;
                  self.errInfo = 'Invalid username or password.';
              } else if (response.status == 200) {
                var datab=response.data
                  sessionStorage.setItem('ms_account',self.user.account);
                  sessionStorage.setItem('ms_password',self.user.password);
                  sessionStorage.setItem('ms_user',JSON.stringify(datab));
                  //self.$router.push('/index');// Page Jump
                  //alert(sessionStorage.getItem("ms_user")); 
              }                            
          }).then((error) => {
              console.log(error);
          })
      } else {
          console.log('error submit!!');
          return false;
      }
    }
},
};
</script>

<style scoped src="../../style/Login.css">
</style>

After successful login, the user information is stored in sessionStorage, 👀 About sessionStorage

Topics: SQLite Vue elementUI