How to build a forum with node+bootstrap

PHPz
Release: 2018-10-13 15:43:06
Original
2040 people have browsed it

This time I will show you how to build a forum with node bootstrap, and what are the precautions for building a forum with node bootstrap. The following is a practical case, let’s take a look.

Preface

After learning koa2 and express and writing some demos, I plan to write a project to practice my skills. Since I am a student, I don’t have any good projects to do. , that is, with the goal of developing a front-end forum, the functional requirements are formulated with reference to some communities, mainly including:

Login and registration

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, comments Paging loading

Follow users

Resource (file) upload, share, download, view

Recommended learning resources...

The 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

Purpose of each module

koa node framework

koa-bodyparser form parsing middleware

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

koa-router 路由中间件

koa-static 静态资源加载中间件

ejs 模板引擎

md5 密码加密

moment 时间中间件

mysql 数据库

koa-views 模板呈现中间件

koa-static-cache 文件缓存

项目基本框架搭建

配置数据库连接

在config文件夹新建default.js :

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

然后在lib文件夹新建mysql.js:

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

这里建立了一个数据库连接池和封装了一个操作数据库表的函数,如果对于数据库连接有不懂的话请自行百度。

建立入口文件

在主目录新建index.js,即项目入口文件:

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

上面代码都有注释,我就不一一说明了,由于资源分享和个人日记还没写,所以暂时统一share...替代。

接下来向mysql.js添加数据库操作语句,建表、增删改查。

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

总共六张表:用户表、文章表、文章评论表、文章收藏表、文章点赞表、用户关注表。

这里引用了外键,但是现在的开发不推荐使用外键了,所以你们可以自行修改,这里在项目第一次启动时会出现数据库创建失败(由于外键原因),只要重新启动就ok了,如果对mysql还不了解的,这里附送大家一个传送门:mysql入门视频教程 密码:c2q7 。

前端页面开发

项目基本结构搭建好后,就可以进行前端页面的编写了。用node开发web时我们一般会配合模板引擎,这个项目我采用的是ejs,除了ejs之外较为常用的还有jade,但是jade相对ejs来说的话代码结构不够清晰。关于ejs语法,这里做个简单的介绍:

header.ejs

    Myblog    
Copy after login

nav.ejs


   
Copy after login

login.ejs

用户注册

来吧骚年们!

已有账号? 登录

Copy after login

footer.ejs

 
Copy after login

header为页面头部结构,nav为页面导航条,login为登录、注册内容、footer为页面顶部结构。可以看到我在ejs文件里有很多的if else 判断语句,这是根据session来判断用户是否登录渲染不同的内容。现在我们需要我们的页面编写样式:分别是home.css和index.css

为了增强对原生js的理解,在项目里我用了大量的原生ajax(显然jquery封装的ajax比较好哈哈),因此这里先编写一个原生ajax请求:

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

实现登录注册

前端基本页面开发好后,我们就可以写后台登录接口了:

注册: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

密码采用md5加密,注册后为用户创建session并将其添加到数据库,写完别忘了在最后加上module.exports = router将接口暴露出来。

登录: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

退出登录: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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Bootstrap教程

vue-element怎么做出音乐播放器

The above is the detailed content of How to build a forum with node+bootstrap. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!