github地址
https://github.com/wclimb/Koa2-blog
使用方式:
1、clone到本地
2、在mysql中建立名字为nodesql的数据库
3、$ cd Koa2-blog npm install
npm i -g supervisor
4、$ supervisor --harmony index
- config 存放默认文件
- lib 存放操作数据库文件
- middlewares 存放判断登录与否文件
- public 存放样式文件
- routes 存放路由文件
- views 存放模板文件
- index 程序主文件
- package.json 包括项目名、作者、依赖等等
接着安装包,安装之前我们使用cnpm安装
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
$ cnpm i koa koa-bodyparser koa-mysql-session koa-router koa-session-minimal koa-static koa-views md5 moment mysql ejs --save
-
koa node
框架 -
koa-bodyparser
表单解析中间件 -
koa-mysql-session
、koa-session-minimal
处理数据库的中间件 -
koa-router
路由中间件 -
koa-static
静态资源加载中间件 -
ejs
模板引擎 -
md5
密码加密 -
moment
时间中间件 -
mysql
数据库 -
koa-views
模板呈现中间件
配置config
const config = {
// 启动端口
port: 3000,
// 数据库配置
database: {
DATABASE: 'nodesql',
USERNAME: 'root',
PASSWORD: '',
PORT: '3306',
HOST: 'localhost',
//CHARSET:'utf-8'
}
}
module.exports = config
Nodejs使用MysQL的连接池
使用连接池可以帮助我们更好的管理数据库连接。数据库连接池可以限制连接的最大数量,复用已有的连接等。
首先,我们需要创建一个连接池:
var mysql = require('mysql');
var pool = mysql.createPool({
host : “hostName”,
user : “username”,
password: “password”
});
其次,我们可以从创建的连接池中获取到一个我们需要的连接:
pool.getConnection(function(err, connection){
});
使用回调函数的参数connection来查询数据库。最后使用connection.realease()方法释放数据库连接。
pool.getConnection(function(err, connection){
connection.query( “select * from table1”, function(err, rows){
if(err) {
throw err;
}else{
console.log( rows );
}
});
connection.release();
});
koa-bodyparser表单解析
Usage
var Koa = require('koa');
var bodyParser = require('koa-bodyparser');
var app = new Koa();
app.use(bodyParser());
app.use(async ctx => {
// the parsed body will store in ctx.request.body
// if nothing was parsed, body will be an empty object {}
ctx.body = ctx.request.body;
});
// 这里我们先通过查找有没有类似/posts?author=XXX 的连接跳转,如果有就执行下面这句话,把用户名取下来,由于用户名存在中文,所以我们进行解码
if (ctx.request.querystring) {
console.log('ctx.request.querystring',decodeURIComponent(ctx.request.querystring.split('=')[1]))
await userModel.findDataByUser(decodeURIComponent(ctx.request.querystring.split('=')[1]))
.then(result=>{
res=JSON.parse(JSON.stringify(result))
console.log(res)
})
await ctx.render('posts',{
session:ctx.session,
posts:res
})
}else{
二、服务器如何获取浏览器提交的数据?
1.获取POST数据:context.Request.Form[“txtname”]
2.获取GET参数:context.Request.QueryString[“txtname1”]
三、服务器如何向浏览器输出数据?
1. 服务器向浏览器输出文本内容:
context.Response.ContentType = "text/plain";
context.Response.Write(“我是从服务器输出到浏览器的数据!:)”);
//Response 允许开发人员对当前页面的输出流进行操作
//write:直接在页面上输出内容,将内容存在httpwriter中的char数组
2.服务器向浏览器输出js代码:
context.Response.ContentType = "text/html";
context.Response.Write("<script>alert('格式错误');</script>");
3.redirect:重定向到另外一个页面,服务其发送命令让浏览器跳转
原理:服务器向浏览器发送一个包含302状态码和Location的响应报文,浏览器看到302后就会自动请求Location指定的页面。Response.Redirect(location);
4.end:立即输出Response里保存的响应报文数据,并停止当前页面代码的执行。Response.End();
request.querystring
Get raw query string void of ?
.
request.querystring=
Set raw query string.
req.querystring
获取查询参数字符串(url中?后面的部分),不包含 ?。
req.querystring=
设置查询参数。