github地址javascript
https://github.com/wclimb/Koa2-bloghtml
使用方式:java
一、clone到本地node
二、在mysql中创建名字为nodesql的数据库mysql
三、$ cd Koa2-blog npm install
git
npm i -g supervisor
github
四、$ supervisor --harmony index
sql
接着安装包,安装以前咱们使用cnpm安装数据库
1
|
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
|
1
|
$ 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
模板呈现中间件
配置confignpm
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(); });
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{
2、服务器如何获取浏览器提交的数据?
1.获取POST数据:context.Request.Form[“txtname”]
2.获取GET参数:context.Request.QueryString[“txtname1”]
3、服务器如何向浏览器输出数据?
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();
Get raw query string void of ?
.
Set raw query string.
获取查询参数字符串(url中?后面的部分),不包含 ?。
设置查询参数。
原文网址:http://www.wclimb.site/2017/07/12/Node-Koa2-Mysql-%E6%90%AD%E5%BB%BA%E7%AE%80%E6%98%93%E5%8D%9A%E5%AE%A2/