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/