脚本宝典收集整理的这篇文章主要介绍了

node项目实战-用node-koa2-mysql-bootstrap搭建一个前端论坛

脚本宝典小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助你少写一行代码,多一份安全和惬意。
<p><code></p> <h2 id="articleHeader0"><strong>前言</strong></h2> <p>在学习了koa2和express并写了一些demo后,打算自己写一个项目练练手,由于是在校生,没什么好的项目做,即以开发一个前端论坛为目标,功能需求参照一下一些社区拟定,主要有:</p> <ol> <li>登录注册</li> <li>个人信息维护、头像等基本信息</li> <li>发表文章,富文本编辑器采用wangEditor插件,编辑、删除文章,文章分类等</li> <li>文章评论、文章收藏、点赞等</li> <li>支持文章分页、评论分页加载</li> <li>关注取关用户</li> <li>资源(文件)上传分享、下载、查看</li> <li>学习资源推荐.....</li> </ol> <p>作者个人日记<br />but。。。。由于种种原因,目前仅实现了部分功能,资源分享还没写<br />项目运行效果:<a href="http://120.77.211.212/home" rel="nofollow noreferrer" target="_blank"></a><a href="http://120.77.211.212/home" rel="nofollow noreferrer" target="_blank">http://120.77.211.212/home</a></p> <p>项目技术栈应用:<a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a>-koa2-ejs-bootstrap3—jquery, github地址:<a href="https://github.com/Jay214/myblog-koa2" rel="nofollow noreferrer" target="_blank">https://github.com/Jay214/myb...</a>,如果觉得对你有帮助或者还看得下去,欢迎star~~鼓励鼓励我这前端渣渣辉。</p> <h2 id="articleHeader1"><strong>开发环境</strong></h2> <p><a href="http://www.js-code.com/tag/node" title="node" target="_blank">node</a>: v8.3.0</p> <p>koa: ^2.4.1</p> <p>mysql: 5.7.1</p> <p>npm: 5.3.0及以上</p> <h2 id="articleHeader2"><strong>如何运行项目</strong></h2> <p>将项目clone至本地 git clone git@github.com:Jay214/myblog-koa2.git<br />安装模块中间件 npm <a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>st<a href="http://www.js-code.com/tag/all" title="all" target="_blank">all</a><br />安装mysql<br />mysql版本推荐使用5.7以下的,5.7的有个bug,图形化界面推荐使用navicat <a href="http://www.js-code.com/tag/for" title="for" target="_blank">for</a> mysql<br />运行可以安装<a href="http://www.js-code.com/tag/super" title="super" target="_blank">super</a>visor(npm <a href="http://www.js-code.com/tag/in" title="in" target="_blank">in</a>st<a href="http://www.js-code.com/tag/all" title="all" target="_blank">all</a> <a href="http://www.js-code.com/tag/super" title="super" target="_blank">super</a>visor 项目运行工具,开启后即处于监听模式,修改文件后保存即可,无需再启动项目) <a href="http://www.js-code.com/tag/node" title="浏览关于“node”的文章" target="_blank" class="tag_link">node</a> <a href="http://www.js-code.com/tag/in" title="浏览关于“in”的文章" target="_blank" class="tag_link">in</a>dex 或npm <a href="http://www.js-code.com/tag/super" title="super" target="_blank">super</a>visor index<br />localhost:8080/home 端口号可自行修改<br />若发现项目有存在什么bug或有比较好的建议欢迎多多提议,qq:2752402930。</p> <h2 id="articleHeader3"><strong>准备工作</strong></h2> <p>由于koa2是基于<a href="http://www.js-code.com/tag/es6" title="es6" target="_blank">es6</a>的promise和es7的await/async语法,所以如果对<a href="http://www.js-code.com/tag/es6" title="es6" target="_blank">es6</a>/es7不懂的话请先过一遍文档,后台搭建数据库是关键,所以请先安装好mysql,mysql建议安装5.7版本以下的,因为5.7.0版本有个bug,需要更改配置文件,具体若你们安装的时候便知道了。</p> <p>安装node环境,使用node -v查看node版本,node需要较新版本能够支持<a href="http://www.js-code.com/tag/es6" title="浏览关于“es6”的文章" target="_blank" class="tag_link">es6</a>的promise和es7的await/async语法,现在node版本都会自带npm的,所以不需要再去安装npm。</p> <h2 id="articleHeader4"><strong>项目结构</strong></h2> <p><span class="img-wrap"><img data-src="/img/bV9ZZ9?w=263&amp;h=307" src="https://static.segmentfault.com/v-5cc2cd8e/global/img/squares.svg" alt="clipboard.png" title="clipboard.png" style="cursor: pointer;"></span></p> <p>1.config存放默认文件(数据库连接配置)<br />2.lib存放数据库文件<br />3.middlewares存放判断登陆注册与否中间件<br />4.<a href="http://www.js-code.com/tag/public" title="public" target="_blank">public</a>存放静态文件,js,引用bootstrap框架等文件<br />5.routers存放路由文件<br />6.views存放模板文件<br />7.index是程序主文件,定义接口,数据库接口,引用模块等<br />8.<a href="http://www.js-code.com/tag/package" title="package" target="_blank">package</a>.json项目的配置文件,包括项目名,作者,依赖,模块等</p> <p>项目用vscode开发的,用起来很舒服,还没尝试过的小伙伴赶紧去试一下吧。<br />项目初始化:cd myblog1 -&gt; npm init 此时已经创建好了<a href="http://www.js-code.com/tag/package" title="package" target="_blank">package</a>.json文件了。</p> <p>由于koa2是轻量级的框架,小巧精悍,所以我们为了促进我们的开发效率和方便性,我们需要安装一些koa2的模块中间件:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="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 " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs sql"><code>npm <span class="hljs-keyword">inst<a href="http://www.js-code.com/tag/all" title="浏览关于“all”的文章" target="_blank" class="tag_link">all</a></span> i koa koa-bodyparser koa-mysql-<span class="hljs-keyword">session</span> koa-router koa-<span class="hljs-keyword">session</span>-minimal koa-<span class="hljs-keyword"><a href="http://www.js-code.com/tag/static" title="浏览关于“static”的文章" target="_blank" class="tag_link">static</a></span> koa-views <span class="hljs-keyword">md5</span> moment mysql ejs koa-<span class="hljs-keyword">static</span>-<span class="hljs-keyword">cache</span> <span class="hljs-comment">--save-dev</span> </code></pre> <h2 id="articleHeader5">各模块用处</h2> <p>koa node框架<br />koa-bodyparser 表单解析中间件<br />koa-mysql-session、koa-session-minimal 处理数据库的中间件<br />koa-router 路由中间件<br />koa-<a href="http://www.js-code.com/tag/static" title="static" target="_blank">static</a> 静态资源加载中间件<br />ejs 模板引擎<br />md5 密码加密<br />moment 时间中间件<br />mysql 数据库<br />koa-views 模板呈现中间件<br />koa-<a href="http://www.js-code.com/tag/static" title="static" target="_blank">static</a>-cache 文件缓存</p> <h2 id="articleHeader6">项目基本框架搭建</h2> <p>配置数据库连接<br />在config文件夹新建<a href="http://www.js-code.com/tag/default" title="default" target="_blank">default</a>.js :</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const config = { //启动端口 port: 8080, //数据库配置 database: { DATABASE: 'nodesql', USERNAME: 'root', PASSWORD: '123456', PORT: '3306', HOST: 'localhost' } } module.exports = config; " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs java"><code><span class="hljs-keyword"><a href="http://www.js-code.com/tag/const" title="浏览关于“const”的文章" target="_blank" class="tag_link">const</a></span> config = { <span class="hljs-comment">//启动端口 </span> port: <span class="hljs-number">8080</span>, <span class="hljs-comment">//数据库配置 </span> database: { DATABASE: <span class="hljs-string">'nodesql'</span>, USERNAME: <span class="hljs-string">'root'</span>, PASSWORD: <span class="hljs-string">'123456'</span>, PORT: <span class="hljs-string">'3306'</span>, HOST: <span class="hljs-string">'localhost'</span> } } <span class="hljs-keyword">module</span>.<span class="hljs-keyword"><a href="http://www.js-code.com/tag/export" title="浏览关于“export”的文章" target="_blank" class="tag_link">export</a>s</span> = config; </code></pre> <p>然后在lib文件夹新建mysql.js:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="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)=>{<br /> pool.getConnection(function (err,connection) {<br /> if(err){ reject(err);<br /> }else{<br /> connection.query(sql,values,(err,rows)=>{<br /> if(err){<br /> reject(err);<br /> }else{<br /> resolve(rows);<br /> }<br /> connection.release(); //为每一个请求都建立一个connection使用完后调用connection.release(); 直接释放资源。<br /> //query用来操作数据库表<br /> })<br /> }<br /> })<br /> })}" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword"><a href="http://www.js-code.com/tag/var" title="浏览关于“var”的文章" target="_blank" class="tag_link">var</a></span> mysql = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mysql'</span>); <span class="hljs-keyword">var</span> config = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../config/<a href="http://www.js-code.com/tag/default" title="浏览关于“default”的文章" target="_blank" class="tag_link">default</a>.js'</span>) <span class="hljs-comment">//建立数据库连接池</span> <span class="hljs-keyword">var</span> pool = mysql.createPool({ host: config.database.HOST, user: config.database.USERNAME, <a href="http://www.js-code.com/tag/password" title="浏览关于“password”的文章" target="_blank" class="tag_link">password</a>: config.database.PASSWORD, database: config.database.DATABASE }); <span class="hljs-keyword"><a href="http://www.js-code.com/tag/let" title="浏览关于“let”的文章" target="_blank" class="tag_link">let</a></span> query = <span class="hljs-function"><span class="hljs-keyword"><a href="http://www.js-code.com/tag/function" title="浏览关于“function”的文章" target="_blank" class="tag_link">function</a></span>(<span class="hljs-params">sql, values</span>) </span>{ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/return" title="浏览关于“return”的文章" target="_blank" class="tag_link">return</a></span> <span class="hljs-keyword"><a href="http://www.js-code.com/tag/new" title="浏览关于“new”的文章" target="_blank" class="tag_link">new</a></span> <span class="hljs-built_in"><a href="http://www.js-code.com/tag/promise" title="浏览关于“Promise”的文章" target="_blank" class="tag_link">Promise</a></span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>)=&gt;</span>{ pool.getConnection(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err,connection</span>) </span>{ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/if" title="浏览关于“if”的文章" target="_blank" class="tag_link">if</a></span>(err){ reject(err); }<span class="hljs-keyword"><a href="http://www.js-code.com/tag/else" title="浏览关于“else”的文章" target="_blank" class="tag_link">else</a></span>{ connection.query(sql,values,<span class="hljs-function">(<span class="hljs-params">err,rows</span>)=&gt;</span>{ <span class="hljs-keyword">if</span>(err){ reject(err); }<span class="hljs-keyword">else</span>{ resolve(rows); } connection.release(); <span class="hljs-comment">//为每一个请求都建立一个connection使用完后调用connection.release(); 直接释放资源。 </span> <span class="hljs-comment">//query用来操作数据库表</span> }) } }) })}</code></pre> <p>这里建立了一个数据库连接池和封装了一个操作数据库表的函数,如果对于数据库连接有不懂的话请自行百度。</p> <h2 id="articleHeader7">建立入口文件</h2> <p>在主目录新建index.js,即项目入口文件:</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="const koa = require(&quot;koa&quot;); //node框架 const path = require(&quot;path&quot;); const bodyParser = require(&quot;koa-bodyparser&quot;); //表单解析中间件 const ejs = require(&quot;ejs&quot;); //模板引擎 const session = require(&quot;koa-session-minimal&quot;); //处理数据库的中间件 const MysqlStore = require(&quot;koa-mysql-session&quot;); //处理数据库的中间件 const router = require(&quot;koa-router&quot;); //路由中间件 const config = require('./config/default.js'); //引入默认文件 const views = require(&quot;koa-views&quot;); //模板呈现中间件 const koaStatic = require(&quot;koa-static&quot;); //静态资源加载中间件 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({ &quot;formLimit&quot;:&quot;5mb&quot;, &quot;jsonLimit&quot;:&quot;5mb&quot;, &quot;textLimit&quot;:&quot;5mb&quot; })); //使用新建的路由文件 //登录 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}`) " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs php"><code><span class="hljs-keyword">const</span> koa = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa"</span>); <span class="hljs-comment">//node框架</span> <span class="hljs-keyword">const</span> path = <span class="hljs-keyword">require</span>(<span class="hljs-string">"path"</span>); <span class="hljs-keyword">const</span> bodyParser = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-bodyparser"</span>); <span class="hljs-comment">//表单解析中间件</span> <span class="hljs-keyword">const</span> ejs = <span class="hljs-keyword">require</span>(<span class="hljs-string">"ejs"</span>); <span class="hljs-comment">//模板引擎</span> <span class="hljs-keyword">const</span> session = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-session-minimal"</span>); <span class="hljs-comment">//处理数据库的中间件</span> <span class="hljs-keyword">const</span> MysqlStore = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-mysql-session"</span>); <span class="hljs-comment">//处理数据库的中间件</span> <span class="hljs-keyword">const</span> router = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-router"</span>); <span class="hljs-comment">//路由中间件</span> <span class="hljs-keyword">const</span> config = <span class="hljs-keyword">require</span>(<span class="hljs-string">'./config/default.js'</span>); <span class="hljs-comment">//引入默认文件</span> <span class="hljs-keyword">const</span> views = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-views"</span>); <span class="hljs-comment">//模板呈现中间件</span> <span class="hljs-keyword">const</span> koaStatic = <span class="hljs-keyword">require</span>(<span class="hljs-string">"koa-static"</span>); <span class="hljs-comment">//静态资源加载中间件</span> <span class="hljs-keyword">const</span> staticCache = <span class="hljs-keyword">require</span>(<span class="hljs-string">'koa-static-cache'</span>) <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> koa(); <span class="hljs-comment">//session存储配置,将session存储至数据库</span> <span class="hljs-keyword">const</span> sessionMysqlConfig = { user: config.database.USERNAME, password: config.database.PASSWORD, database: config.database.DATABASE, host: config.database.HOST, } <span class="hljs-comment">//配置session中间件</span> app.<span class="hljs-keyword">use</span>(session({ key: <span class="hljs-string">'USER_SID'</span>, store: <span class="hljs-keyword">new</span> MysqlStore(sessionMysqlConfig) })) <span class="hljs-comment">//配置静态资源加载中间件</span> app.<span class="hljs-keyword">use</span>(koaStatic( path.join(__dir<a href="http://www.js-code.com/tag/name" title="浏览关于“name”的文章" target="_blank" class="tag_link">name</a> , <span class="hljs-string">'./<a href="http://www.js-code.com/tag/public" title="浏览关于“public”的文章" target="_blank" class="tag_link">public</a>'</span>) )) <span class="hljs-comment">//配置服务端模板渲染引擎中间件</span> app.<span class="hljs-keyword">use</span>(views(path.join(__dirname, <span class="hljs-string">'./views'</span>),{ extension: <span class="hljs-string">'ejs'</span> })) <span class="hljs-comment">//使用表单解析中间件</span> app.<span class="hljs-keyword">use</span>(bodyParser({ <span class="hljs-string">"<a href="http://www.js-code.com/tag/form" title="浏览关于“form”的文章" target="_blank" class="tag_link">form</a>Limit"</span>:<span class="hljs-string">"5mb"</span>, <span class="hljs-string">"jsonLimit"</span>:<span class="hljs-string">"5mb"</span>, <span class="hljs-string">"<a href="http://www.js-code.com/tag/text" title="浏览关于“text”的文章" target="_blank" class="tag_link">text</a>Limit"</span>:<span class="hljs-string">"5mb"</span> })); <span class="hljs-comment">//使用新建的路由文件</span> <span class="hljs-comment">//登录</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signin.js'</span>).routes()) <span class="hljs-comment">//注册</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signup.js'</span>).routes()) <span class="hljs-comment">//退出登录</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signout.js'</span>).routes()) <span class="hljs-comment">//首页</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/home.js'</span>).routes()) <span class="hljs-comment">//个人主页</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/personal'</span>).routes()) <span class="hljs-comment">//文章页</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/articles'</span>).routes()) <span class="hljs-comment">//资源分享</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/share'</span>).routes()) <span class="hljs-comment">//个人日记</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/<a href="http://www.js-code.com/tag/self" title="浏览关于“self”的文章" target="_blank" class="tag_link">self</a>Note'</span>).routes()) <span class="hljs-comment">//监听在8080端口</span> app.listen(<span class="hljs-number">8080</span>) console.log(`listening on port ${config.port}`) </code></pre> <p>上面代码都有注释,我就不一一说明了,由于资源分享和个人日记还没写,所以暂时统一share...替代。</p> <p>接下来向mysql.js添加数据库操作语句,建表、增删改查。。。</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="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 = &quot;insert into users(name,pass) values(?,?);&quot; return query(_sql,value); } //更新头像 let updateUserImg = function(value){ let _sql = &quot;update users set avator=? where id=?&quot; return query(_sql,value); } //更新用户信息 let updateUser = function(value){ let _sql = &quot;update users set name=?,job=?,company=?,introdu=?,userhome=?,github=? where id=?&quot; return query(_sql,value); } //发表文章 let insertPost = function(value){ let _sql = &quot;insert into posts(name,title,content,uid,moment,type,avator) values(?,?,?,?,?,?,?);&quot; return query(_sql,value); } //更新文章评论数 let updatePostComment = function(value){ let _sql = &quot;update posts set comments=? where id=?&quot; return query(_sql,value); } ......." title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs php"><code><span class="hljs-keyword">var</span> users = `create table <span class="hljs-keyword">if</span> not exists users( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, name VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, pass VARCHAR(<span class="hljs-number">40</span>) NOT <span class="hljs-keyword">NULL</span>, avator VARCHAR(<span class="hljs-number">100</span>) <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'default.jpg'</span>, job VARCHAR(<span class="hljs-number">40</span>), company VARCHAR(<span class="hljs-number">40</span>), <a href="http://www.js-code.com/tag/int" title="浏览关于“int”的文章" target="_blank" class="tag_link">int</a>rodu VARCHAR(<span class="hljs-number">255</span>), userhome VARCHAR(<span class="hljs-number">100</span>), github VARCHAR(<span class="hljs-number">100</span>), PRIMARY KEY (id) );` <span class="hljs-keyword">var</span> posts = `create table <span class="hljs-keyword">if</span> not exists posts( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, name VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, title VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, content TEXT NOT <span class="hljs-keyword">NULL</span>, uid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span>, moment VARCHAR(<span class="hljs-number">40</span>) NOT <span class="hljs-keyword">NULL</span>, comments VARCHAR(<span class="hljs-number">255</span>) NOT <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'0'</span>, pv VARCHAR(<span class="hljs-number">40</span>) NOT <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'0'</span>, likes INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'0'</span>, type VARCHAR(<span class="hljs-number">20</span>) NOT <span class="hljs-keyword">NULL</span>, avator VARCHAR(<span class="hljs-number">100</span>), collection INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'0'</span>, PRIMARY KEY (id) , FOREIGN KEY (uid) REFERENCES users(id) ON DELETE CASCADE );` <span class="hljs-keyword">var</span> comment= `create table <span class="hljs-keyword">if</span> not exists comment( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, name VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, content TEXT NOT <span class="hljs-keyword">NULL</span>, moment VARCHAR(<span class="hljs-number">40</span>) NOT <span class="hljs-keyword">NULL</span>, postid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span>, avator VARCHAR(<span class="hljs-number">100</span>), PRIMARY KEY ( id ), FOREIGN KEY (postid) REFERENCES posts(id) ON DELETE CASCADE );` <span class="hljs-keyword">var</span> likes = `create table <span class="hljs-keyword">if</span> not exists likes( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, name VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, postid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span>, PRIMARY KEY (id), FOREIGN KEY (postid) REFERENCES posts(id) ON DELETE CASCADE );` <span class="hljs-keyword">var</span> collection = `create table <span class="hljs-keyword">if</span> not exists collection( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, uid VARCHAR(<span class="hljs-number">100</span>) NOT <span class="hljs-keyword">NULL</span>, postid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span>, PRIMARY KEY (id), FOREIGN KEY (postid) REFERENCES posts(id) ON DELETE CASCADE );` <span class="hljs-keyword">var</span> follow = `create table <span class="hljs-keyword">if</span> not exists follow( id INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> AUTO_INCREMENT, uid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span>, fwid INT(<span class="hljs-number">200</span>) NOT <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-string">'0'</span>, PRIMARY KEY (id), FOREIGN KEY (uid) REFERENCES users(id) ON DELETE CASCADE ) ` let createTable = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(sql)</span></span>{ <span class="hljs-keyword">return</span> query(sql, []); } <span class="hljs-comment">//建表</span> createTable(users); createTable(posts); createTable(comment); createTable(likes); createTable(collection); createTable(follow); <span class="hljs-comment">//createTable(follower);</span> <span class="hljs-comment">//注册用户</span> let insertData = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(value)</span></span>{ let _sql = <span class="hljs-string">"insert into users(name,pass) values(?,?);"</span> <span class="hljs-keyword">return</span> query(_sql,value); } <span class="hljs-comment">//更新头像</span> let updateUserImg = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(value)</span></span>{ let _sql = <span class="hljs-string">"update users set avator=? where id=?"</span> <span class="hljs-keyword">return</span> query(_sql,value); } <span class="hljs-comment">//更新用户信息</span> let updateUser = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(value)</span></span>{ let _sql = <span class="hljs-string">"update users set name=?,job=?,company=?,introdu=?,userhome=?,github=? where id=?"</span> <span class="hljs-keyword">return</span> query(_sql,value); } <span class="hljs-comment">//发表文章</span> let insertPost = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(value)</span></span>{ let _sql = <span class="hljs-string">"insert into posts(name,title,content,uid,moment,type,avator) values(?,?,?,?,?,?,?);"</span> <span class="hljs-keyword">return</span> query(_sql,value); } <span class="hljs-comment">//更新文章评论数</span> let updatePostComment = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(value)</span></span>{ let _sql = <span class="hljs-string">"update posts set comments=? where id=?"</span> <span class="hljs-keyword">return</span> query(_sql,value); } .......</code></pre> <p>总共六张表:用户表、文章表、文章评论表、文章收藏表、文章点赞表、用户关注表。</p> <p>这里引用了外键,但是现在的开发不推荐使用外键了,所以你们可以自行修改,这里在项目第一次启动时会出现数据库创建失败(由于外键原因),只要重新启动就ok了,如果对mysql还不了解的,这里附送大家一个传送门:mysql入门视频教程 密码:c2q7 。</p> <h2 id="articleHeader8">前端页面开发</h2> <p>项目基本结构搭建好后,就可以进行前端页面的编写了。用node开发web时我们一般会配合模板引擎,这个项目我采用的是ejs,除了ejs之外较为常用的还有jade,但是jade相对ejs来说的话代码结构不够清晰。关于ejs语法,这里做个简单的介绍:<br />header.ejs</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>="<!DOCTYPE html><br /> <html lang=&quot;en&quot;><br /> <head><br /> <meta charset=&quot;utf-8&quot;><br /> <title>Myblog</title> <link rel=&quot;stylesheet&quot; href=&quot;/css/bootstrap.min.css&quot;> <link rel=&quot;stylesheet&quot; href=&quot;/css/index.css&quot;> <script src=&quot;/js/jquery-3.2.1.min.js&quot; type=&quot;text/javascript&quot;></script><br /> <script src=&quot;/js/bootstrap.min.js&quot; type=&quot;text/javascript&quot;></script></p> <p>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code><span class="hljs-meta">&lt;!DOCTYPE html&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr"><a href="http://www.js-code.com/tag/char" title="浏览关于“char”的文章" target="_blank" class="tag_link">char</a>set</span>=<span class="hljs-string">"utf-8"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Myblog<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name"><a href="http://www.js-code.com/tag/link" title="浏览关于“link”的文章" target="_blank" class="tag_link">link</a></span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/css/bootstrap.min.css"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/css/index.css"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/js/jquery-3.2.1.min.js"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/<a href="http://www.js-code.com/tag/java" title="浏览关于“java”的文章" target="_blank" class="tag_link">java</a>script"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/js/bootstrap.min.js"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/javascript"</span>&gt;</span><span class="undefined"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> </code></pre> <ul> <li> <p>nav.ejs</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="button" target="_blank">button</a>" <a href="http://www.js-code.com/tag/class" title="class" target="_blank">class</a>="copyCode code-tool" data-toggle="tooltip" data-placement="<a href="http://www.js-code.com/tag/top" title="top" target="_blank">top</a>" data-clipboard-<a href="http://www.js-code.com/tag/text" title="text" target="_blank">text</a>=" </head><br /> <body></p> <header class=&quot;nav-head&quot;> <div class=&quot;nav container&quot;> <ul> <li><a href=&quot;/home&quot;>首页</a></li> <li> <a href=&quot;/share&quot;>资源分享</a></li> <li> <a href=&quot;/share&quot;>推荐</a></li> <li> <a href=&quot;/share&quot;>个人日记</a></li> <li><a href=&quot;/about&quot;>关于作者</a></li> <li><input type=&quot;text&quot; placeholder=&quot;搜索&quot; class=&quot;input-sm search&quot;></li> <p> <% if(session.user){ %></p> <li> <img src=&quot;/<a href="http://www.js-code.com/tag/images" title="浏览关于“images”的文章" target="_blank" class="tag_link">images</a>/<%= session.avator %>&quot; alt=&quot;&quot; class=&quot;img-circle img-title&quot;></p> <ul class=&quot;menu&quot;> <li class=&quot;personal menulist&quot;><a href=&quot;/personal/<%= session.user %>&quot;>主页</a></li> <p> <!-- <li class=&quot;collection menulist&quot;><a href=&quot;#&quot;>收藏集</a></li> --></p> <li class=&quot;menulist&quot;><a href=&quot;/articles&quot;>写文章</a></li> <li class=&quot;out&quot;><a href=&quot;/signout&quot;>登出</a></li> </ul> </li> <p> <script> var imgTitle = document.getElementsByClassName('img-title')[0],</p> <p> menu = document.getElementsByClassName('menu')[0]; imgTitle.onclick = function (event) { showTap(); event.stopPropagation(); }</p> <p> document.body.addEventListener('click',function (event) { menu.style.display = 'none'; // event.stopPropagation(); },true)</p> <p> 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&amp;&amp;xhr.status>=200&amp;&amp;xhr.<a href="http://www.js-code.com/tag/status" title="status" target="_blank">status</a><300){ <a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a> text = xhr.responseText; //服务器返回的对象 <a href="http://www.js-code.com/tag/if" title="if" target="_blank">if</a>(text){ win<a href="http://www.js-code.com/tag/do" title="do" target="_blank">do</a>w.<a href="http://www.js-code.com/tag/location" title="location" target="_blank">location</a>.reload = 'localhost:8080/home'; }</p> <p> } }</p> <p> }*/ </script><br /> <% }else{ %></p> <li class=&quot;login&quot;> <a class=&quot;loginup&quot; href=&quot;javascript:;&quot;><span class=&quot;glyphicon glyphicon-user&quot;></span> 注册 | 登录</a></p> </li> <p> <% } %></p> </ul></div> </header> <p> <script></p> <p> <a href="http://www.js-code.com/tag/var" title="var" target="_blank">var</a> searchInput = <a href="http://www.js-code.com/tag/document" title="document" target="_blank">document</a>.getElementsBy<a href="http://www.js-code.com/tag/class" title="Class" target="_blank">Class</a>Name('search')[0]; searchInput.on<a href="http://www.js-code.com/tag/focus" title="focus" target="_blank">focus</a> = <a href="http://www.js-code.com/tag/function" title="function" target="_blank">function</a> () { <a href="http://www.js-code.com/tag/this" title="this" target="_blank">this</a>.style.width = &quot;300px&quot;; } searchInput.on<a href="http://www.js-code.com/tag/blur" title="blur" target="_blank">blur</a> = <a href="http://www.js-code.com/tag/function" title="function" target="_blank">function</a> () { <a href="http://www.js-code.com/tag/this" title="this" target="_blank">this</a>.style.width = &quot;180px&quot;; }</p> <p> </script></p> <p>" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code> <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav-head"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name"><a href="http://www.js-code.com/tag/div" title="浏览关于“div”的文章" target="_blank" class="tag_link">div</a></span> <span class="hljs-attr">class</span>=<span class="hljs-string">"nav container"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/home"</span>&gt;</span>首页<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/share"</span>&gt;</span>资源分享<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/share"</span>&gt;</span>推荐<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/share"</span>&gt;</span>个人日记<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/about"</span>&gt;</span>关于作者<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"搜索"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-sm search"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">%</span> <span class="hljs-attr">if</span>(<span class="hljs-attr">session.user</span>){ %&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/<a href="http://www.js-code.com/tag/image" title="浏览关于“image”的文章" target="_blank" class="tag_link">image</a>s/&lt;%= session.avator %&gt;"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"img-circle img-title"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"menu"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"personal menulist"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/personal/&lt;%= session.user %&gt;"</span>&gt;</span>主页<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-comment">&lt;!-- &lt;li class="collection menulist"&gt;&lt;a href="#"&gt;收藏集&lt;/a&gt;&lt;/li&gt; --&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"menulist"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/articles"</span>&gt;</span>写文章<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"out"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/signout"</span>&gt;</span>登出<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript"> <span class="hljs-keyword">var</span> imgTitle = <span class="hljs-built_in"><a href="http://www.js-code.com/tag/document" title="浏览关于“document”的文章" target="_blank" class="tag_link">document</a></span>.getElementsBy<a href="http://www.js-code.com/tag/class" title="浏览关于“Class”的文章" target="_blank" class="tag_link">Class</a>Name(<span class="hljs-string">'img-title'</span>)[<span class="hljs-number">0</span>], menu = <span class="hljs-built_in"><a href="http://www.js-code.com/tag/do" title="浏览关于“do”的文章" target="_blank" class="tag_link">do</a>cument</span>.getElementsByClassName(<span class="hljs-string">'menu'</span>)[<span class="hljs-number">0</span>]; imgTitle.<a href="http://www.js-code.com/tag/onclick" title="浏览关于“onclick”的文章" target="_blank" class="tag_link">onclick</a> = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"><a href="http://www.js-code.com/tag/event" title="浏览关于“event”的文章" target="_blank" class="tag_link">event</a></span>) </span>{ showTap(); event.s<a href="http://www.js-code.com/tag/top" title="浏览关于“top”的文章" target="_blank" class="tag_link">top</a><a href="http://www.js-code.com/tag/prop" title="浏览关于“Prop”的文章" target="_blank" class="tag_link">Prop</a>agation(); } <span class="hljs-built_in">document</span>.body.addEventListener(<span class="hljs-string">'click'</span>,<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{ menu.style.display = <span class="hljs-string">'none'</span>; <span class="hljs-comment">// event.stopPropagation();</span> },<span class="hljs-literal"><a href="http://www.js-code.com/tag/true" title="浏览关于“true”的文章" target="_blank" class="tag_link">true</a></span>) <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showTap</span>(<span class="hljs-params"></span>)</span>{ <span class="hljs-keyword">if</span>(menu.style.display == <span class="hljs-string">'block'</span>){ menu.style.display = <span class="hljs-string">'none'</span>; }<span class="hljs-keyword">else</span> { menu.style.display = <span class="hljs-string">'block'</span>; } } <span class="hljs-comment">//退出登录</span> <span class="hljs-keyword">var</span> signOut = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'out'</span>)[<span class="hljs-number">0</span>]; <span class="hljs-comment">/* signOut.onclick = function(){ ajax('get','/signout',<a href="http://www.js-code.com/tag/null" title="浏览关于“null”的文章" target="_blank" class="tag_link">null</a>); xhr.onreadystatechange = function () { if(xhr.ready<a href="http://www.js-code.com/tag/state" title="浏览关于“State”的文章" target="_blank" class="tag_link">State</a>==4&amp;&amp;xhr.<a href="http://www.js-code.com/tag/status" title="浏览关于“status”的文章" target="_blank" class="tag_link">status</a>&gt;=200&amp;&amp;xhr.status&lt;300){ let text = xhr.responseText; //服务器返回的对象 if(text){ <a href="http://www.js-code.com/tag/window" title="浏览关于“window”的文章" target="_blank" class="tag_link">window</a>.<a href="http://www.js-code.com/tag/location" title="浏览关于“location”的文章" target="_blank" class="tag_link">location</a>.reload = 'localhost:8080/home'; } } } }*/</span> </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">%</span> }<span class="hljs-attr">else</span>{ %&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"login"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"loginup"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"javascript:;"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"glyphicon glyphicon-user"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> 注册 | 登录<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">%</span> } %&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript"> <span class="hljs-keyword">var</span> searchInput = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'search'</span>)[<span class="hljs-number">0</span>]; searchInput.<a href="http://www.js-code.com/tag/onfocus" title="浏览关于“onfocus”的文章" target="_blank" class="tag_link">onfocus</a> = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword"><a href="http://www.js-code.com/tag/this" title="浏览关于“this”的文章" target="_blank" class="tag_link">this</a></span>.style.width = <span class="hljs-string">"300px"</span>; } searchInput.<a href="http://www.js-code.com/tag/onblur" title="浏览关于“onblur”的文章" target="_blank" class="tag_link">onblur</a> = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">this</span>.style.width = <span class="hljs-string">"180px"</span>; } </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> </code></pre> <ul> <li></li> </ul> </li> <li>login.ejs</li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="<a href="http://www.js-code.com/tag/button" title="浏览关于“button”的文章" target="_blank" class="tag_link">button</a>" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="</p> <div class=&quot;sign&quot;> <a href=&quot;javascript:;&quot; title=&quot;关闭&quot; class=&quot;login-close close&quot;>×</a></p> <div class=&quot;sign-title&quot;> <h1>用户注册</h1> <h3>来吧骚年们!</h3> </p></div> <form class=&quot;form signup&quot; role=&quot;form&quot;> <div class=&quot;form-group&quot;> <input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;账号不少于两个字符&quot; class=&quot;form-control&quot;> </div> <div class=&quot;form-group&quot;> <input type=&quot;password&quot; name=&quot;pass&quot; class=&quot;pass form-control&quot; placeholder=&quot;密码&quot;> </div> <div class=&quot;form-group&quot;> <input type=&quot;password&quot; name=&quot;repeatpass&quot; id=&quot;repeat&quot; placeholder=&quot;重复密码&quot; class=&quot;form-control&quot;> </div> <div class=&quot;form-group&quot;> <input type=&quot;button&quot; value=&quot;注册&quot; class=&quot;btn btn-primary login-up&quot;> </div> </p></form> <form class=&quot;form signin&quot; role=&quot;form&quot;> <div class=&quot;form-group&quot;> <input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;请输入用户名&quot; class=&quot;form-control&quot;> </div> <div class=&quot;form-group&quot;> <input type=&quot;password&quot; name=&quot;pass&quot; class=&quot;pass form-control&quot; placeholder=&quot;请输入密码&quot;> </div> <div class=&quot;form-group&quot;> <input type=&quot;button&quot; value=&quot;登录&quot; class=&quot;btn btn-primary login-in&quot;> </div> </p></form> <div class=&quot;form-tips&quot;> <span>已有账号?</span><br /> <a href=&quot;javascript:;&quot; class=&quot;register&quot;>登录</a> </div> </div> <div class=&quot;login-form-mask&quot;></div> <p><script> // $(document).ready(function () { var $close = $('.login-close'); var $sign = $('.sign'); $close.click(function () { $sign.css(&quot;display&quot;,&quot;none&quot;); })</p> <p> var $register = $('.register'), //login/loginup切换 $span = $('.form-tips span'), $signup = $('.signup'), $signTitle = $('.sign-title h1'), $signin = $('.signin');</p> <p> $register.click(function () { if($span.html() == &quot;已有账号?&quot;){</p> <p> $signin.css('display','block'); $signup.css('display','none'); $(this).html('注册'); $span.html(&quot;没有账号?&quot;); $signTitle.html(&quot;欢迎登录&quot;);</p> <p> }else{</p> <p> $signin.css('display','none'); $signup.css('display','block'); $(this).html('登录'); $span.html(&quot;已有账号?&quot;); $signTitle.html(&quot;欢迎注册&quot;); } })</p> <p> var $loginup = $('.loginup'); //点击登录/注册,阻止事件冒泡 $loginup.click(function () { $mask.fadeIn(100); $sign.slideDown(200); return false; })</p> <p> var $close = $('.login-close'), $mask = $('.login-form-mask'), $sign = $('.sign');</p> <p> $sign.click(function () { return false; })</p> <p> $close.click(function (e) { // e.stopPropagation(); fadeOut();</p> <p> })</p> <p> $(document).click(function (e) { //点击任意位置取消登录框 //e.stopPropagation(); fadeOut(); }) function fadeOut(){ $mask.fadeOut(100); $sign.slideUp(200); }</p> <p> var loginUp = document.getElementsByClassName('login-up')[0], loginIn = document.getElementsByClassName('login-in')[0], signUp = document.getElementsByClassName('signup')[0], signIn = document.getElementsByClassName('signin')[0];</p> <p> loginUp.onclick = function () { //注册 var data1 = 'username=' + signUp[&quot;username&quot;].value + '&amp;' + 'pass='+ signUp[&quot;pass&quot;].value + '&amp;' + 'repeatpass=' + signUp[&quot;repeatpass&quot;].value; var reg = /^[u4E00-u9FA5]{2,5}$/; /* if(!reg.test(signUp[&quot;username&quot;].value)){ signUp[&quot;username&quot;].classList.add(&quot;tips&quot;); signUp['username'].value() } */ ajax('post','/signup',data1,&quot;application/x-www-form-urlencoded&quot;); xhr.onreadystatechange = function () { if(xhr.readyState==4&amp;&amp;xhr.status>=200&amp;&amp;xhr.<a href="http://www.js-code.com/tag/status" title="status" target="_blank">status</a><300){ let text = JSON.parse(xhr.responseText).code; console.log(text) //服务器返回的对象 if(text == 3){ fadeOut(); alert(&quot;注册成功&quot;) setTimeout(()=>{ <a href="http://www.js-code.com/tag/window" title="window" target="_blank">window</a>.<a href="http://www.js-code.com/tag/location" title="location" target="_blank">location</a>.reload(); },1000) // <a href="http://www.js-code.com/tag/do" title="do" target="_blank">do</a>cument.getElementsBy<a href="http://www.js-code.com/tag/class" title="Class" target="_blank">Class</a>Name('login')[0].outer<a href="http://www.js-code.com/tag/html" title="HTML" target="_blank">HTML</a> = &quot;</p> <li class='users'><a href='/'>&quot;+signUp[&quot;username&quot;].value+ &quot;(=^ ^=)&quot; +&quot;</a></li> <p>&quot; }else{ fadeOut(); alert(&quot;用户已存在&quot;) }</p> <p> } }</p> <p> }</p> <p> loginIn.onclick = function () { //登录 var data2 = 'username=' + signIn[&quot;username&quot;].value + '&amp;' + 'pass=' + signIn[&quot;pass&quot;].value; ajax('post','/signin',data2,&quot;application/x-www-form-urlencoded&quot;); xhr.onreadystatechange = function () { if(xhr.readyState==4&amp;&amp;xhr.status>=200&amp;&amp;xhr.status<300){ <a href="http://www.js-code.com/tag/let" title="let" target="_blank">let</a> text = JSON.parse(xhr.responseText).code; //服务器返回的对象 console.log(text);</p> <p> // <a href="http://www.js-code.com/tag/document" title="document" target="_blank">document</a>.getElementsByClassName('login')[0].outer<a href="http://www.js-code.com/tag/html" title="HTML" target="_blank">HTML</a> = &quot;</p> <li class='users'><a href='/'>&quot;+signUp[&quot;username&quot;].value+ &quot;(=^ ^=)&quot; +&quot;</a></li> <p>&quot; if(text===1){ fadeOut(); // let imgTitle = document.getElementsByClassName('img-title')[0]; // imgTitle.setAttribute('src','/images/' + JSON.parse(xhr.responseText).avator) setTimeout(()=>{ <a href="http://www.js-code.com/tag/window" title="window" target="_blank">window</a>.location.reload(); },1000) }<a href="http://www.js-code.com/tag/else" title="else" target="_blank">else</a> <a href="http://www.js-code.com/tag/if" title="if" target="_blank">if</a>(text === 2){ <a href="http://www.js-code.com/tag/alert" title="alert" target="_blank">alert</a>('密码错误') }<a href="http://www.js-code.com/tag/else" title="else" target="_blank">else</a>{ <a href="http://www.js-code.com/tag/alert" title="alert" target="_blank">alert</a>('账号不存在') }</p> <p> } }</p> <p> } </script><br /> " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sign"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"javascript:;"</span> <span class="hljs-attr">title</span>=<span class="hljs-string">"关闭"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"login-<a href="http://www.js-code.com/tag/close" title="浏览关于“close”的文章" target="_blank" class="tag_link">close</a> close"</span>&gt;</span>×<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sign-title"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>用户注册<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>来吧骚年们!<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name"><a href="http://www.js-code.com/tag/for" title="浏览关于“for”的文章" target="_blank" class="tag_link">for</a>m</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form signup"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"form"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"账号不少于两个字符"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"pass"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pass form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"密码"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"repeatpass"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"repeat"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"重复密码"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"注册"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary login-up"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form signin"</span> <span class="hljs-attr">role</span>=<span class="hljs-string">"form"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"请输入用户名"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"pass"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pass form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"请输入密码"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"登录"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-primary login-in"</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-tips"</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>已有账号?<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"javascript:;"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"register"</span>&gt;</span>登录<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"login-form-mask"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript"> <span class="hljs-comment">// $(document).ready(function () {</span> <span class="hljs-keyword">var</span> $close = $(<span class="hljs-string">'.login-close'</span>); <span class="hljs-keyword">var</span> $sign = $(<span class="hljs-string">'.sign'</span>); $close.click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ $sign.css(<span class="hljs-string">"display"</span>,<span class="hljs-string">"none"</span>); }) <span class="hljs-keyword">var</span> $register = $(<span class="hljs-string">'.register'</span>), <span class="hljs-comment">//login/loginup切换</span> $span = $(<span class="hljs-string">'.form-tips span'</span>), $signup = $(<span class="hljs-string">'.signup'</span>), $signTitle = $(<span class="hljs-string">'.sign-title h1'</span>), $signin = $(<span class="hljs-string">'.signin'</span>); $register.click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">if</span>($span.html() == <span class="hljs-string">"已有账号?"</span>){ $signin.css(<span class="hljs-string">'display'</span>,<span class="hljs-string">'block'</span>); $signup.css(<span class="hljs-string">'display'</span>,<span class="hljs-string">'none'</span>); $(<span class="hljs-keyword">this</span>).html(<span class="hljs-string">'注册'</span>); $span.html(<span class="hljs-string">"没有账号?"</span>); $signTitle.html(<span class="hljs-string">"欢迎登录"</span>); }<span class="hljs-keyword">else</span>{ $signin.css(<span class="hljs-string">'display'</span>,<span class="hljs-string">'none'</span>); $signup.css(<span class="hljs-string">'display'</span>,<span class="hljs-string">'block'</span>); $(<span class="hljs-keyword">this</span>).html(<span class="hljs-string">'登录'</span>); $span.html(<span class="hljs-string">"已有账号?"</span>); $signTitle.html(<span class="hljs-string">"欢迎注册"</span>); } }) <span class="hljs-keyword">var</span> $loginup = $(<span class="hljs-string">'.loginup'</span>); <span class="hljs-comment">//点击登录/注册,阻止事件冒泡</span> $loginup.click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ $mask.fadeIn(<span class="hljs-number">100</span>); $sign.slideDown(<span class="hljs-number">200</span>); <span class="hljs-keyword">return</span> <span class="hljs-literal"><a href="http://www.js-code.com/tag/false" title="浏览关于“false”的文章" target="_blank" class="tag_link">false</a></span>; }) <span class="hljs-keyword">var</span> $close = $(<span class="hljs-string">'.login-close'</span>), $mask = $(<span class="hljs-string">'.login-form-mask'</span>), $sign = $(<span class="hljs-string">'.sign'</span>); $sign.click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }) $close.click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{ <span class="hljs-comment">// e.stopPropagation();</span> fadeOut(); }) $(<span class="hljs-built_in">document</span>).click(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{ <span class="hljs-comment">//点击任意位置取消登录框</span> <span class="hljs-comment">//e.stopPropagation();</span> fadeOut(); }) <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fadeOut</span>(<span class="hljs-params"></span>)</span>{ $mask.fadeOut(<span class="hljs-number">100</span>); $sign.slideUp(<span class="hljs-number">200</span>); } <span class="hljs-keyword">var</span> loginUp = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'login-up'</span>)[<span class="hljs-number">0</span>], loginIn = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'login-in'</span>)[<span class="hljs-number">0</span>], signUp = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'signup'</span>)[<span class="hljs-number">0</span>], signIn = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'signin'</span>)[<span class="hljs-number">0</span>]; loginUp.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//注册</span> <span class="hljs-keyword">var</span> data1 = <span class="hljs-string">'username='</span> + signUp[<span class="hljs-string">"username"</span>].value + <span class="hljs-string">'&amp;'</span> + <span class="hljs-string">'pass='</span>+ signUp[<span class="hljs-string">"pass"</span>].value + <span class="hljs-string">'&amp;'</span> + <span class="hljs-string">'repeatpass='</span> + signUp[<span class="hljs-string">"repeatpass"</span>].value; <span class="hljs-keyword">var</span> reg = <span class="hljs-regexp">/^[u4E00-u9FA5]{2,5}$/</span>; <span class="hljs-comment">/* if(!reg.test(signUp["username"].value)){ signUp["username"].classList.add("tips"); signUp['username'].value() } */</span> ajax(<span class="hljs-string">'post'</span>,<span class="hljs-string">'/signup'</span>,data1,<span class="hljs-string">"application/x-www-form-urlencoded"</span>); xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">if</span>(xhr.readyState==<span class="hljs-number">4</span>&amp;&amp;xhr.status&gt;=<span class="hljs-number">200</span>&amp;&amp;xhr.status&lt;<span class="hljs-number">300</span>){ <span class="hljs-keyword">let</span> text = <span class="hljs-built_in">JSON</span>.parse(xhr.responseText).code; <span class="hljs-built_in">console</span>.log(text) <span class="hljs-comment">//服务器返回的对象</span> <span class="hljs-keyword">if</span>(text == <span class="hljs-number">3</span>){ fadeOut(); <a href="http://www.js-code.com/tag/alert" title="浏览关于“alert”的文章" target="_blank" class="tag_link">alert</a>(<span class="hljs-string">"注册成功"</span>) <a href="http://www.js-code.com/tag/setTimeout" title="浏览关于“setTimeout”的文章" target="_blank" class="tag_link">setTimeout</a>(<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{ <span class="hljs-built_in">window</span>.location.reload(); },<span class="hljs-number">1000</span>) <span class="hljs-comment">// document.getElementsByClassName('login')[0].outer<a href="http://www.js-code.com/tag/html" title="浏览关于“HTML”的文章" target="_blank" class="tag_link">HTML</a> = "&lt;li class='users'&gt;&lt;a href='/'&gt;"+signUp["username"].value+ "(=^ ^=)" +"&lt;/a&gt;&lt;/li&gt;"</span> }<span class="hljs-keyword">else</span>{ fadeOut(); alert(<span class="hljs-string">"用户已存在"</span>) } } } } loginIn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-comment">//登录</span> <span class="hljs-keyword">var</span> data2 = <span class="hljs-string">'username='</span> + signIn[<span class="hljs-string">"username"</span>].value + <span class="hljs-string">'&amp;'</span> + <span class="hljs-string">'pass='</span> + signIn[<span class="hljs-string">"pass"</span>].value; ajax(<span class="hljs-string">'post'</span>,<span class="hljs-string">'/signin'</span>,data2,<span class="hljs-string">"application/x-www-form-urlencoded"</span>); xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">if</span>(xhr.readyState==<span class="hljs-number">4</span>&amp;&amp;xhr.status&gt;=<span class="hljs-number">200</span>&amp;&amp;xhr.status&lt;<span class="hljs-number">300</span>){ <span class="hljs-keyword">let</span> text = <span class="hljs-built_in">JSON</span>.parse(xhr.responseText).code; <span class="hljs-comment">//服务器返回的对象</span> <span class="hljs-built_in">console</span>.log(text); <span class="hljs-comment">// document.getElementsByClassName('login')[0].outerHTML = "&lt;li class='users'&gt;&lt;a href='/'&gt;"+signUp["username"].value+ "(=^ ^=)" +"&lt;/a&gt;&lt;/li&gt;"</span> <span class="hljs-keyword">if</span>(text===<span class="hljs-number">1</span>){ fadeOut(); <span class="hljs-comment">// let imgTitle = document.getElementsByClassName('img-title')[0];</span> <span class="hljs-comment">// imgTitle.setAttribute('src','/images/' + JSON.parse(xhr.responseText).avator)</span> setTimeout(<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{ <span class="hljs-built_in">window</span>.location.reload(); },<span class="hljs-number">1000</span>) }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(text === <span class="hljs-number">2</span>){ alert(<span class="hljs-string">'密码错误'</span>) }<span class="hljs-keyword">else</span>{ alert(<span class="hljs-string">'账号不存在'</span>) } } } } </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> </code></pre> <ul> <li>footer.ejs</li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text=" </body><br /> </html><br /> " title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs xml"><code> <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span> </code></pre> <p>header为页面头部结构,nav为页面导航条,login为登录、注册内容、footer为页面顶部结构。可以看到我在ejs文件里有很多的if else 判断语句,这是根据session来判断用户是否登录渲染不同的内容。现在我们需要我们的页面编写样式:分别是home.css和index.css</p> <p>为了增强对原生js的理解,在项目里我用了大量的原生ajax(显然jquery封装的ajax比较好哈哈),因此这里先编写一个原生ajax请求:</p> <ul> <li>ajax.js</li> </ul> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="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(&quot;Microsoft.XMLHTTP&quot;); }else { alert('你的浏览器不支持ajax'); return false; } xhr.onerror = function (err) { alert(&quot;some err have hapened:&quot;,err); } xhr.open(method,url,true); if(method==&quot;post&quot;){ xhr.setRequestHeader(&quot;Content-type&quot;,types); // xhr.setRequestHeader(&quot;Conent-Type&quot;,'application/json'&quot;application/x-www-form-urlencoded&quot;) } try{ setTimeout(()=>{<br /> xhr.send(data);<br /> },0);<br /> }catch(err) {<br /> alert(&quot;some error have hapened in font:&quot;,err);<br /> }<br /> return xhr;<br /> }" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs javascript"><code><span class="hljs-keyword">var</span> xhr = <span class="hljs-literal">null</span>; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ajax</span>(<span class="hljs-params">method,url,data,types</span>) </span>{ <span class="hljs-comment">//封装一个ajax方法</span> <span class="hljs-comment">// var text;</span> <span class="hljs-keyword">if</span>(<span class="hljs-built_in">window</span>.XMLHttpRequest){ xhr = <span class="hljs-keyword">new</span> XMLHttpRequest(); }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(<span class="hljs-built_in">window</span>.ActiveX<a href="http://www.js-code.com/tag/Object" title="浏览关于“Object”的文章" target="_blank" class="tag_link">Object</a>){ xhr = <span class="hljs-keyword">new</span> ActiveXObject(<span class="hljs-string">"Microsoft.XMLHTTP"</span>); }<span class="hljs-keyword">else</span> { alert(<span class="hljs-string">'你的浏览器不支持ajax'</span>); <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; } xhr.<a href="http://www.js-code.com/tag/onerror" title="浏览关于“onerror”的文章" target="_blank" class="tag_link">onerror</a> = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{ alert(<span class="hljs-string">"some err have hapened:"</span>,err); } xhr.<a href="http://www.js-code.com/tag/open" title="浏览关于“open”的文章" target="_blank" class="tag_link">open</a>(method,url,<span class="hljs-literal">true</span>); <span class="hljs-keyword">if</span>(method==<span class="hljs-string">"post"</span>){ xhr.setRequestHeader(<span class="hljs-string">"Content-type"</span>,types); <span class="hljs-comment">// xhr.setRequestHeader("Conent-Type",'application/json'"application/x-www-form-urlencoded")</span> } <span class="hljs-keyword"><a href="http://www.js-code.com/tag/try" title="浏览关于“try”的文章" target="_blank" class="tag_link">try</a></span>{ setTimeout(<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{ xhr.send(data); },<span class="hljs-number">0</span>); }<span class="hljs-keyword"><a href="http://www.js-code.com/tag/catch" title="浏览关于“catch”的文章" target="_blank" class="tag_link">catch</a></span>(err) { alert(<span class="hljs-string">"some error have hapened in font:"</span>,err); } <span class="hljs-keyword">return</span> xhr; }</code></pre> <h2 id="articleHeader9">实现登录注册</h2> <p>前端基本页面开发好后,我们就可以写后台登录接口了:</p> <p>注册:signup.js</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="var router = require('koa-router')(); var userModel = require('../lib/mysql.js'); var md5 = require('md5') // 注册页面 // post 注册 router.post('/signup', async(ctx, next) => {<br /> console.log(ctx.request.body)<br /> var user = {<br /> name: ctx.request.body.username,<br /> pass: ctx.request.body.pass,<br /> repeatpass: ctx.request.body.repeatpass<br /> }<br /> let flag = 0;<br /> await userModel.findDataByName(user.name)<br /> .then(result => {<br /> console.log(result)<br /> if (result.length) {</p> <p> //处理err<br /> console.log('用户已存在')<br /> ctx.body = {<br /> code: 1<br /> }; </p> <p> } else if (user.pass !== user.repeatpass || user.pass == '') {<br /> ctx.body = { //应把这个逻辑放到前端<br /> code: 2<br /> };</p> <p> } else {<br /> flag = 1; </p> <p> }<br /> })<br /> if(flag==1){<br /> let res = await userModel.insertData([user.name, md5(user.pass + 'asd&amp;$BH&amp;*') ])<br /> console.log(res.insertId)<br /> await userModel.findDataByName(user.name)<br /> .then((result)=>{</p> <p> // var res = JSON.parse(JSON.stringify(result))<br /> console.log(result[0]['avator'])<br /> ctx.session.id = res.insertId;<br /> ctx.session.user=user.name;<br /> ctx.session.avator = 'default.jpg';<br /> ctx.body = {<br /> code: 3<br /> };<br /> console.log('注册成功')<br /> })<br /> }</p> <p>})</p> <p>module.exports = router" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">var</span> router = <span class="hljs-built_in">require</span>(<span class="hljs-string">'koa-router'</span>)(); <span class="hljs-keyword">var</span> userModel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../lib/mysql.js'</span>); <span class="hljs-keyword">var</span> md5 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'md5'</span>) <span class="hljs-comment">// 注册页面</span> <span class="hljs-comment">// post 注册</span> router.post(<span class="hljs-string">'/signup'</span>, <span class="hljs-keyword">async</span>(ctx, next) =&gt; { <span class="hljs-built_in">console</span>.log(ctx.request.body) <span class="hljs-keyword">var</span> user = { name: ctx.request.body.username, pass: ctx.request.body.pass, repeatpass: ctx.request.body.repeatpass } <span class="hljs-keyword">let</span> flag = <span class="hljs-number">0</span>; <span class="hljs-keyword">await</span> userModel.findDataByName(user.name) .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(result) <span class="hljs-keyword">if</span> (result.<a href="http://www.js-code.com/tag/length" title="浏览关于“length”的文章" target="_blank" class="tag_link">length</a>) { <span class="hljs-comment">//处理err</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'用户已存在'</span>) ctx.body = { code: <span class="hljs-number">1</span> }; } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (user.pass !== user.repeatpass || user.pass == <span class="hljs-string">''</span>) { ctx.body = { <span class="hljs-comment">//应把这个逻辑放到前端</span> code: <span class="hljs-number">2</span> }; } <span class="hljs-keyword">else</span> { flag = <span class="hljs-number">1</span>; } }) <span class="hljs-keyword">if</span>(flag==<span class="hljs-number">1</span>){ <span class="hljs-keyword">let</span> res = <span class="hljs-keyword">await</span> userModel.insertData([user.name, md5(user.pass + <span class="hljs-string">'asd&amp;$BH&amp;*'</span>) ]) <span class="hljs-built_in">console</span>.log(res.insertId) <span class="hljs-keyword">await</span> userModel.findDataByName(user.name) .then(<span class="hljs-function">(<span class="hljs-params">result</span>)=&gt;</span>{ <span class="hljs-comment">// var res = JSON.parse(JSON.stringify(result))</span> <span class="hljs-built_in">console</span>.log(result[<span class="hljs-number">0</span>][<span class="hljs-string">'avator'</span>]) ctx.session.id = res.insertId; ctx.session.user=user.name; ctx.session.avator = <span class="hljs-string">'default.jpg'</span>; ctx.body = { code: <span class="hljs-number">3</span> }; <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'注册成功'</span>) }) } }) <span class="hljs-built_in">module</span>.exports = router</code></pre> <p>密码采用md5加密,注册后为用户创建session并将其添加到数据库,写完别忘了在最后加上module.<a href="http://www.js-code.com/tag/export" title="export" target="_blank">export</a>s = router将接口暴露出来。</p> <p>登录:signin.js</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="var router = require('koa-router')(); var userModel = require('../lib/mysql.js') var md5 = require('md5') router.post('/signin', async(ctx, next) => {<br /> console.log(ctx.request.body)<br /> var name = ctx.request.body.username;<br /> var pass = ctx.request.body.pass;</p> <p> await userModel.findDataByName(name)<br /> .then(result => {</p> <p> var res = JSON.parse(JSON.stringify(result))</p> <p> if (name === res[0]['name']&amp;&amp;(md5(pass + 'asd&amp;$BH&amp;*') === res[0]['pass'])) {<br /> console.log('登录成功')<br /> ctx.body = {<br /> code: 1,<br /> }</p> <p> ctx.session.user = res[0]['name']<br /> ctx.session.id = res[0]['id']<br /> ctx.session.avator = res[0]['avator'] </p> <p> }else if(md5(pass + 'asd&amp;$BH&amp;*') != res[0]['pass']){<br /> ctx.body = {<br /> code: 2 //密码错误<br /> }<br /> }<br /> }).catch(err => {<br /> ctx.body = {<br /> code: 3 //账号不存在+<br /> }<br /> console.log('用户名或密码错误!')</p> <p> })</p> <p>})</p> <p>module.exports = router" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs typescript"><code><span class="hljs-keyword">var</span> router = <span class="hljs-built_in">require</span>(<span class="hljs-string">'koa-router'</span>)(); <span class="hljs-keyword">var</span> userModel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../lib/mysql.js'</span>) <span class="hljs-keyword">var</span> md5 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'md5'</span>) router.post(<span class="hljs-string">'/signin'</span>, <span class="hljs-keyword">async</span>(ctx, next) =&gt; { <span class="hljs-built_in">console</span>.log(ctx.request.body) <span class="hljs-keyword">var</span> name = ctx.request.body.username; <span class="hljs-keyword">var</span> pass = ctx.request.body.pass; <span class="hljs-keyword">await</span> userModel.findDataByName(name) .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> { <span class="hljs-keyword">var</span> res = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(result)) <span class="hljs-keyword">if</span> (name === res[<span class="hljs-number">0</span>][<span class="hljs-string">'name'</span>]&amp;&amp;(md5(pass + <span class="hljs-string">'asd&amp;$BH&amp;*'</span>) === res[<span class="hljs-number">0</span>][<span class="hljs-string">'pass'</span>])) { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'登录成功'</span>) ctx.body = { code: <span class="hljs-number">1</span>, } ctx.session.user = res[<span class="hljs-number">0</span>][<span class="hljs-string">'name'</span>] ctx.session.id = res[<span class="hljs-number">0</span>][<span class="hljs-string">'id'</span>] ctx.session.avator = res[<span class="hljs-number">0</span>][<span class="hljs-string">'avator'</span>] }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(md5(pass + <span class="hljs-string">'asd&amp;$BH&amp;*'</span>) != res[<span class="hljs-number">0</span>][<span class="hljs-string">'pass'</span>]){ ctx.body = { code: <span class="hljs-number">2</span> <span class="hljs-comment">//密码错误</span> } } }).catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> { ctx.body = { code: <span class="hljs-number">3</span> <span class="hljs-comment">//账号不存在+</span> } <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'用户名或密码错误!'</span>) }) }) <span class="hljs-built_in">module</span>.exports = router</code></pre> <p>退出登录:signout.js</p> <div class="widget-codetool" style="display:none;"> <div class="widget-codetool--inner"> <span class="selectCode code-tool" data-toggle="tooltip" data-placement="top" title="" data-original-title="全选"></span><br /> <span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="//使用新建的路由文件 //登录 app.use(require('./routers/signin.js').routes()) //注册 app.use(require('./routers/signup.js').routes()) //退出登录 app.use(require('./routers/signout.js').routes())" title="" data-original-title="复制"></span> </div> </p></div> <pre class="hljs php"><code><span class="hljs-comment">//使用新建的路由文件</span> <span class="hljs-comment">//登录</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signin.js'</span>).routes()) <span class="hljs-comment">//注册</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signup.js'</span>).routes()) <span class="hljs-comment">//退出登录</span> app.<span class="hljs-keyword">use</span>(<span class="hljs-keyword">require</span>(<span class="hljs-string">'./routers/signout.js'</span>).routes())</code></pre> <p>登录注册完成,由于学习繁忙,内容只能一点一点写了,后续内容持续更新。。。</p> <p></code></p>

总结

以上是脚本宝典为你收集整理的

node项目实战-用node-koa2-mysql-bootstrap搭建一个前端论坛

全部内容,希望文章能够帮你解决

node项目实战-用node-koa2-mysql-bootstrap搭建一个前端论坛

所遇到的程序开发问题,欢迎加入QQ群277859234一起讨论学习。如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典网站推荐给程序员好友。 本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。

80%的人都看过