Home > Web Front-end > JS Tutorial > body text

node+koa2+mysql+bootstrap builds forum front-end and back-end

php中世界最好的语言
Release: 2019-02-26 16:01:18
Original
3476 people have browsed it

This time I will bring you node koa2 mysql bootstrap to build the front and back ends of the forum. What are the precautions for building the front and back ends of the forum with node koa2 mysql bootstrap. Here are the practical cases. Let’s go together. take a look.

Recommended related mysql video tutorials: "mysql tutorial"

Foreword

After learning koa2 and express After writing some demos, I plan to write a project myself to practice my skills. Since I am a student in school, I don’t have any good projects to do. I aim to develop a front-end forum. The functional requirements are formulated with reference to some communities. The main ones are:

Login and register

Personal information maintenance, avatar and other basic information

Publish articles, the rich text editor uses the wangEditor plug-in, edit, delete articles, article classification, etc.

Article comments, article collections, likes, etc.

Supports article paging and comment paging loading

Follow and unfollow users

Upload and share resources (files), Download and view

Recommended learning resources...

Author's personal diary

but. . . . Due to various reasons, only some functions have been implemented so far, and resource sharing has not yet been written.

Project operation effect: http://120.77.211.212/home

Project technology stack application: node-koa2- ejs-bootstrap3—jquery, github address: https://github.com/Jay214/myblog-koa2. If you find it helpful or you can still read it, please star~~ encourage me as a front-end scumbag.

Development environment

node: v8.3.0

koa: ^2.4.1

mysql: 5.7.1

npm: 5.3.0 and above

How to run the project

Clone the project to local git clone git@github.com:Jay214/myblog-koa2 .git

Install module middleware npm install

Install mysql

Mysql version is recommended to be below 5.7, 5.7 has a bug, graphical The interface recommends using navicat for MySQL

You can install supervisor (npm install supervisor project running tool, it will be in monitoring mode after opening it, just save it after modifying the file, no need to start the project again) node index or npm supervisor index

localhost:8080/home The port number can be modified by yourself

If you find any bugs in the project or have better suggestions, please feel free to make suggestions, qq: 2752402930.

Preparation

Since koa2 is based on es6's promise and es7's await/async syntax, if you don't understand es6/es7, please read the document first. Building the database in the background is the key, so please install mysql first. Mysql is recommended to be installed below version 5.7, because version 5.7.0 has a bug and the configuration file needs to be changed. You will know the details when you install it.

Install the node environment and use node -v to check the node version. Node needs a newer version to support the promise of es6 and the await/async syntax of es7. Now the node version will come with npm, so there is no need to go there. Install npm.

Project structure

1.config stores the default file (database connection configuration)

2.lib stores Database file

3.middlewares stores the middleware that determines whether to log in and register or not

4.public stores static files, js, references to bootstrap framework and other files

5.routers stores routes File

6.views stores template files

7.index is the main file of the program, defining interfaces, database interfaces, reference modules, etc.

8.package.json project configuration Files, including project name, author, dependencies, modules, etc.

The project was developed with vscode. It is very comfortable to use. If you haven’t tried it yet, please go and try it.

Project initialization: cd myblog1 -> npm init The package.json file has been created at this time.

Since koa2 is a lightweight framework, small and compact, in order to promote our development efficiency and convenience, we need to install some koa2 module middleware:

npm install i koa koa-bodyparser koa-mysql-session koa-router koa-session-minimal koa-static koa-views md5 moment mysql ejs koa-static-cache --save-dev
Copy after login

Use of each module

koa node framework

koa-bodyparser form parsing middleware

koa-mysql-session, koa-session -minimal middleware for processing database

koa-router routing middleware

koa-static static resource loading middleware

ejs template engine

md5 password Encryption

moment time middleware

mysql database

koa-views template rendering middleware

koa-static-cache file cache

Building the basic framework of the project

Configuring the database connection

Create a new default.js in the config folder:

const config = { 
 //启动端口 
port: 8080,
 //数据库配置 
 database: { 
 DATABASE: 'nodesql', 
 USERNAME: 'root', 
 PASSWORD: '123456', 
 PORT: '3306', 
HOST: 'localhost' 
 }
}
module.exports = config;
Copy after login

Then create a new mysql.js in the lib folder:

var mysql = require('mysql');
var config = require('../config/default.js')
//建立数据库连接池
var pool = mysql.createPool({
 host: config.database.HOST,
 user: config.database.USERNAME,
 password: config.database.PASSWORD,
 database: config.database.DATABASE
});
let query = function(sql, values) { 
return new Promise((resolve, reject)=>{
 pool.getConnection(function (err,connection) {
  if(err){ reject(err);
  }else{  
connection.query(sql,values,(err,rows)=>{ 
   if(err){ 
   reject(err);
   }else{
   resolve(rows); 
   }   
 connection.release(); //为每一个请求都建立一个connection使用完后调用connection.release(); 直接释放资源。 
      //query用来操作数据库表
  })
  } 
  }) 
 })}
Copy after login

A database connection pool is established here and a function that operates the database table is encapsulated. If you don’t understand the database connection, please search it yourself.

Create entry file

Create a new index.js in the main directory, that is, the project entry file:

const koa = require("koa"); //node框架
const path = require("path"); 
const bodyParser = require("koa-bodyparser"); //表单解析中间件
const ejs = require("ejs"); //模板引擎
const session = require("koa-session-minimal"); //处理数据库的中间件
const MysqlStore = require("koa-mysql-session"); //处理数据库的中间件
const router = require("koa-router"); //路由中间件
const config = require('./config/default.js'); //引入默认文件
const views = require("koa-views"); //模板呈现中间件
const koaStatic = require("koa-static"); //静态资源加载中间件
const staticCache = require('koa-static-cache')
const app = new koa();
//session存储配置,将session存储至数据库
const sessionMysqlConfig = {
 user: config.database.USERNAME,
 password: config.database.PASSWORD,
 database: config.database.DATABASE,
 host: config.database.HOST,
}
//配置session中间件
app.use(session({
 key: 'USER_SID',
 store: new MysqlStore(sessionMysqlConfig)
}))
//配置静态资源加载中间件
app.use(koaStatic(
 path.join(dirname , './public')
))
//配置服务端模板渲染引擎中间件
app.use(views(path.join(dirname, './views'),{
 extension: 'ejs'
}))
//使用表单解析中间件
app.use(bodyParser({
 "formLimit":"5mb",
 "jsonLimit":"5mb",
 "textLimit":"5mb"
}));
//使用新建的路由文件
//登录
app.use(require('./routers/signin.js').routes())
//注册
app.use(require('./routers/signup.js').routes())
//退出登录
app.use(require('./routers/signout.js').routes())
//首页
app.use(require('./routers/home.js').routes())
//个人主页
app.use(require('./routers/personal').routes())
//文章页
app.use(require('./routers/articles').routes())
//资源分享
app.use(require('./routers/share').routes())
//个人日记
app.use(require('./routers/selfNote').routes())
//监听在8080端口
app.listen(8080) 
console.log(`listening on port ${config.port}`)
Copy after login

The above code has comments, I will not I explained them one by one. Since the resource sharing and personal diary have not been written yet, I will share them together for the time being... instead.

Next add database operation statements to mysql.js to create tables, add, delete, modify, and query.

var users = `create table if not exists users(
 id INT(200) NOT NULL AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 pass VARCHAR(40) NOT NULL,
 avator VARCHAR(100) DEFAULT 'default.jpg', 
 job VARCHAR(40),
 company VARCHAR(40),
 introdu VARCHAR(255),
 userhome VARCHAR(100),
 github VARCHAR(100),
 PRIMARY KEY (id)
);`
var posts = `create table if not exists posts(
 id INT(200) NOT NULL AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 title VARCHAR(100) NOT NULL,
 content TEXT NOT NULL,
 uid INT(200) NOT NULL,
 moment VARCHAR(40) NOT NULL,
 comments VARCHAR(255) NOT NULL DEFAULT '0',
 pv VARCHAR(40) NOT NULL DEFAULT '0',
 likes INT(200) NOT NULL DEFAULT '0',
 type VARCHAR(20) NOT NULL,
 avator VARCHAR(100),
 collection INT(200) NOT NULL DEFAULT '0', 
 PRIMARY KEY (id) ,
 FOREIGN KEY (uid) REFERENCES users(id)
 ON DELETE CASCADE
);`
var comment= `create table if not exists comment(
 id INT(200) NOT NULL AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 content TEXT NOT NULL,
 moment VARCHAR(40) NOT NULL,
 postid INT(200) NOT NULL,
 avator VARCHAR(100),
 PRIMARY KEY ( id ),
 FOREIGN KEY (postid) REFERENCES posts(id)
 ON DELETE CASCADE
);`
var likes = `create table if not exists likes(
 id INT(200) NOT NULL AUTO_INCREMENT,
 name VARCHAR(100) NOT NULL,
 postid INT(200) NOT NULL,
 PRIMARY KEY (id),
 FOREIGN KEY (postid) REFERENCES posts(id)
 ON DELETE CASCADE
);`
 var collection = `create table if not exists collection(
 id INT(200) NOT NULL AUTO_INCREMENT,
 uid VARCHAR(100) NOT NULL,
 postid INT(200) NOT NULL,
 PRIMARY KEY (id),
 FOREIGN KEY (postid) REFERENCES posts(id) 
 ON DELETE CASCADE
 );`
 var follow = `create table if not exists follow(
  id INT(200) NOT NULL AUTO_INCREMENT,
  uid INT(200) NOT NULL, 
  fwid INT(200) NOT NULL DEFAULT '0',
  PRIMARY KEY (id),
  FOREIGN KEY (uid) REFERENCES users(id)
  ON DELETE CASCADE
 )
 `
let createTable = function(sql){
 return query(sql, []);
}
//建表
createTable(users);
createTable(posts);
createTable(comment);
createTable(likes);
createTable(collection);
createTable(follow);
//createTable(follower);
//注册用户
let insertData = function(value){
 let _sql = "insert into users(name,pass) values(?,?);"
 return query(_sql,value);
}
//更新头像
let updateUserImg = function(value){
 let _sql = "update users set avator=? where id=?"
 return query(_sql,value);
}
//更新用户信息
let updateUser = function(value){
 let _sql = "update users set name=?,job=?,company=?,introdu=?,userhome=?,github=? where id=?"
 return query(_sql,value);
}
//发表文章
let insertPost = function(value){
 let _sql = "insert into posts(name,title,content,uid,moment,type,avator) values(?,?,?,?,?,?,?);"
 return query(_sql,value);
}
//更新文章评论数
let updatePostComment = function(value){
 let _sql = "update posts set comments=? where id=?"
 return query(_sql,value);
}
.......
Copy after login

There are six tables in total: user table, article table, article comment table, article collection table, article like table, and user follow table.

Foreign keys are referenced here, but the use of foreign keys is not recommended in current development, so you can modify it yourself. When the project is started for the first time, the database creation will fail (due to foreign keys). As long as Restarting will be ok. If you don’t know mysql yet, here is a portal for you: mysql introductory video tutorial password: c2q7.

Front-end page development

After the basic structure of the project is established, you can write the front-end page. When using node to develop web, we usually use a template engine. For this project, I used ejs. In addition to ejs, jade is also more commonly used, but compared to ejs, the code structure of jade is not clear enough. Regarding ejs syntax, here is a brief introduction:

header.ejs

<!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="utf-8">
 <title>Myblog</title>
 <link rel="stylesheet" href="/css/bootstrap.min.css" rel="external nofollow" >
 <link rel="stylesheet" href="/css/index.css" rel="external nofollow" >
 <script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
 <script src="/js/bootstrap.min.js" type="text/javascript"></script>
Copy after login

nav.ejs

 </head>
 <body>
 <header class="nav-head">
 <p class="nav container">
  <ul>
  <li><a href="/home" rel="external nofollow" >首页</a></li>
  <li> <a href="/share" rel="external nofollow" rel="external nofollow" rel="external nofollow" >资源分享</a></li>
  <li> <a href="/share" rel="external nofollow" rel="external nofollow" rel="external nofollow" >推荐</a></li>
  <li> <a href="/share" rel="external nofollow" rel="external nofollow" rel="external nofollow" >个人日记</a></li>
  <li><a href="/about" rel="external nofollow" >关于作者</a></li>
  <li><input type="text" placeholder="搜索" class="input-sm search"></li>
  
  <% if(session.user){ %>
   <li>
   <img src="/images/<%= session.avator %>" alt="" class="img-circle img-title">
   
   <ul class="menu">
    <li class="personal menulist"><a href="/personal/<%= session.user %>" rel="external nofollow" >主页</a></li>
   <!-- <li class="collection menulist"><a href="#" rel="external nofollow" >收藏集</a></li>
   -->
    <li class="menulist"><a href="/articles" rel="external nofollow" >写文章</a></li>
    <li class="out"><a href="/signout" rel="external nofollow" >登出</a></li>
   </ul>
   </li>
   <script>
    var imgTitle = document.getElementsByClassName('img-title')[0],
  
    menu = document.getElementsByClassName('menu')[0];
    imgTitle.onclick = function (event) {
    showTap();
    event.stopPropagation();
    }
    
    document.body.addEventListener('click',function (event) { 
    menu.style.display = 'none';
    // event.stopPropagation();
    },true)
 
    function showTap(){
    if(menu.style.display == 'block'){
     menu.style.display = 'none';
    }else {
     menu.style.display = 'block';
    }
    }
    //退出登录
    var signOut = document.getElementsByClassName('out')[0];
   /* signOut.onclick = function(){
    ajax('get','/signout',null);
    xhr.onreadystatechange = function () {
    if(xhr.readyState==4&&xhr.status>=200&&xhr.status<300){
    let text = xhr.responseText; //服务器返回的对象
    if(text){
    window.location.reload = 'localhost:8080/home';
    }
    
    }
   }
    }*/
   </script>
   <% }else{ %>
   <li class="login">
    <a class="loginup" href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span class="glyphicon glyphicon-user"></span> 注册 | 登录</a>
    
    </li>
    <% } %>
  
  </ul>
 </p>
 </header>
 <script>
 
 
 var searchInput = document.getElementsByClassName('search')[0];
 searchInput.onfocus = function () {
  this.style.width = "300px";
 }
 searchInput.onblur = function () {
  this.style.width = "180px";
 }
 
 </script>
Copy after login

login.ejs

<p class="sign">
 <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" title="关闭" class="login-close close">×</a>
 <p class="sign-title">
 <h1>用户注册</h1>
 <h3>来吧骚年们!</h3>
 </p>
 <form class="form signup" role="form">
  <p class="form-group">
  <input type="text" name="username" placeholder="账号不少于两个字符" class="form-control">
  </p>
 <p class="form-group">
  <input type="password" name="pass" class="pass form-control" placeholder="密码">
 </p>
 <p class="form-group">
  <input type="password" name="repeatpass" id="repeat" placeholder="重复密码" class="form-control">
 </p>
  <p class="form-group">
  <input type="button" value="注册" class="btn btn-primary login-up">
  </p>
 </form>
 <form class="form signin" role="form">
 <p class="form-group">
  <input type="text" name="username" placeholder="请输入用户名" class="form-control">
 </p>
 <p class="form-group">
  <input type="password" name="pass" class="pass form-control" placeholder="请输入密码">
 </p>
 <p class="form-group">
  <input type="button" value="登录" class="btn btn-primary login-in">
 </p>
 </form>
 <p class="form-tips">
 <span>已有账号?</span>
 <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="register">登录</a>
 </p>
</p>
<p class="login-form-mask"></p>
<script>
 // $(document).ready(function () {
 var $close = $('.login-close');
 var $sign = $('.sign');
 $close.click(function () {
  $sign.css("display","none");
 })
 var $register = $('.register'), //login/loginup切换
  $span = $('.form-tips span'),
  $signup = $('.signup'),
  $signTitle = $('.sign-title h1'),
  $signin = $('.signin');
 $register.click(function () {
  if($span.html() == "已有账号?"){
  $signin.css('display','block');
  $signup.css('display','none');
  $(this).html('注册');
  $span.html("没有账号?");
  $signTitle.html("欢迎登录");
  }else{
  $signin.css('display','none');
  $signup.css('display','block');
  $(this).html('登录');
  $span.html("已有账号?");
  $signTitle.html("欢迎注册");
  }
 })
 var $loginup = $('.loginup'); //点击登录/注册,阻止事件冒泡
 $loginup.click(function () {
  $mask.fadeIn(100);
  $sign.slideDown(200);
  return false;
 })
 var $close = $('.login-close'),
  $mask = $('.login-form-mask'),
  $sign = $('.sign');
 $sign.click(function () {
  return false;
 })
 $close.click(function (e) {
  // e.stopPropagation();
  fadeOut();
 })
 $(document).click(function (e) { //点击任意位置取消登录框
  //e.stopPropagation();
  fadeOut();
 })
 function fadeOut(){
  $mask.fadeOut(100);
  $sign.slideUp(200);
 }
 
 var loginUp = document.getElementsByClassName('login-up')[0],
 loginIn = document.getElementsByClassName('login-in')[0],
 signUp = document.getElementsByClassName('signup')[0],
 signIn = document.getElementsByClassName('signin')[0];
 
 
 loginUp.onclick = function () { //注册
 var data1 = 'username=' + signUp["username"].value + '&' + 'pass='+ signUp["pass"].value + '&' + 'repeatpass=' + signUp["repeatpass"].value;
 var reg = /^[\u4E00-\u9FA5]{2,5}$/;
 /* if(!reg.test(signUp["username"].value)){
  signUp["username"].classList.add("tips");
  signUp['username'].value()
 } */
 ajax('post','/signup',data1,"application/x-www-form-urlencoded");
 xhr.onreadystatechange = function () {
  if(xhr.readyState==4&&xhr.status>=200&&xhr.status<300){
  let text = JSON.parse(xhr.responseText).code; 
  console.log(text) //服务器返回的对象
  if(text == 3){
   fadeOut();
   alert("注册成功")
   setTimeout(()=>{
   window.location.reload();
  },1000)
  // document.getElementsByClassName('login')[0].outerHTML = "<li class=&#39;users&#39;><a href=&#39;/&#39;>"+signUp["username"].value+ "(=^ ^=)" +"</a></li>"
  }else{
  fadeOut();
  alert("用户已存在")
  }
  
  }
 }
 }
 loginIn.onclick = function () { //登录
 var data2 = 'username=' + signIn["username"].value + '&' + 'pass=' + signIn["pass"].value;
 ajax('post','/signin',data2,"application/x-www-form-urlencoded");
 xhr.onreadystatechange = function () {
  if(xhr.readyState==4&&xhr.status>=200&&xhr.status<300){
  let text = JSON.parse(xhr.responseText).code; //服务器返回的对象
  console.log(text);
  
   // document.getElementsByClassName('login')[0].outerHTML = "<li class=&#39;users&#39;><a href=&#39;/&#39;>"+signUp["username"].value+ "(=^ ^=)" +"</a></li>"
  if(text===1){
  fadeOut();
  // let imgTitle = document.getElementsByClassName('img-title')[0];
  // imgTitle.setAttribute('src','/images/' + JSON.parse(xhr.responseText).avator)
  setTimeout(()=>{
   window.location.reload();
  },1000)
  }else if(text === 2){
   alert('密码错误')
  }else{
   alert('账号不存在')
  }
  
  }
 }
 
 }
</script>
Copy after login

footer.ejs

 </body>
 </html>
Copy after login

header is the page header structure, nav is the page navigation bar, login is the login and registration content, and footer is the top structure of the page. You can see that I have a lot of if else judgment statements in the ejs file. This is based on the session to judge whether the user is logged in and render different content. Now we need to write our page styles: home.css and index.css respectively

In order to enhance the understanding of native js, I used a lot of native ajax in the project (obviously jquery encapsulated ajax is better haha), so here we write a native ajax request:

ajax.js

var xhr = null;
 function ajax(method,url,data,types) { //封装一个ajax方法
 // var text;
 if(window.XMLHttpRequest){
  xhr = new XMLHttpRequest();
 }else if(window.ActiveXObject){
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }else {
  alert('你的浏览器不支持ajax');
  return false;
 }
 
 xhr.onerror = function (err) {
  alert("some err have hapened:",err);
 }
 xhr.open(method,url,true);
 if(method=="post"){
  xhr.setRequestHeader("Content-type",types);
  // xhr.setRequestHeader("Conent-Type",'application/json'"application/x-www-form-urlencoded")
 }
 try{
  setTimeout(()=>{
  xhr.send(data);
 },0);
 }catch(err) {
  alert("some error have hapened in font:",err);
 }
 return xhr;
 }
Copy after login

realize login registration

front-end After the basic page is developed, we can write the backend login interface:

Registration: signup.js

var router = require('koa-router')();
var userModel = require('../lib/mysql.js');
var md5 = require('md5')
 // 注册页面
 
 // post 注册
router.post('/signup', async(ctx, next) => {
 console.log(ctx.request.body)
 var user = {
 name: ctx.request.body.username,
 pass: ctx.request.body.pass,
 repeatpass: ctx.request.body.repeatpass
 }
 let flag = 0;
 await userModel.findDataByName(user.name)
 .then(result => {
  console.log(result)
  if (result.length) {
  
   //处理err
   console.log('用户已存在')
   ctx.body = {
   code: 1
   };  
  
  } else if (user.pass !== user.repeatpass || user.pass == '') {
  ctx.body = { //应把这个逻辑放到前端
   code: 2
  };
  } else {
  flag = 1;  
  
  }
 })
 if(flag==1){
 let res = await userModel.insertData([user.name, md5(user.pass + 'asd&$BH&*') ])
 console.log(res.insertId)
 await userModel.findDataByName(user.name)
 .then((result)=>{
  
  // var res = JSON.parse(JSON.stringify(result))
  console.log(result[0]['avator'])
  ctx.session.id = res.insertId;
  ctx.session.user=user.name;
  ctx.session.avator = 'default.jpg';
  ctx.body = {
  code: 3
  };
  console.log('注册成功')
  })
 }
})
module.exports = router
Copy after login

The password is encrypted with md5. After registration, a session is created for the user and added to the database. , don’t forget to add module.exports = router at the end to expose the interface.

Log in: signin.js

var router = require('koa-router')();
var userModel = require('../lib/mysql.js')
var md5 = require('md5')
router.post('/signin', async(ctx, next) => {
 console.log(ctx.request.body)
 var name = ctx.request.body.username;
 var pass = ctx.request.body.pass;
 await userModel.findDataByName(name)
 .then(result => {
  var res = JSON.parse(JSON.stringify(result))
  if (name === res[0]['name']&&(md5(pass + 'asd&$BH&*') === res[0]['pass'])) {
   console.log('登录成功')
   ctx.body = {
   code: 1,
   }
 
   ctx.session.user = res[0]['name']
   ctx.session.id = res[0]['id']
   ctx.session.avator = res[0]['avator'] 
  }else if(md5(pass + 'asd&$BH&*') != res[0]['pass']){
  ctx.body = {
   code: 2 //密码错误
  }
  }
 }).catch(err => {
  ctx.body = {
  code: 3 //账号不存在+
  }
  console.log('用户名或密码错误!')
 })
})
module.exports = router
Copy after login

Log out: signout.js

//使用新建的路由文件
//登录
app.use(require('./routers/signin.js').routes())
//注册
app.use(require('./routers/signup.js').routes())
//退出登录
app.use(require('./routers/signout.js').routes())
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese website Other related articles!

Recommended reading:

vue-element makes music player function (with code)

How to use vue to implement View personal information and change password

The above is the detailed content of node+koa2+mysql+bootstrap builds forum front-end and back-end. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template