1.访问静态文件: 使用中间件koa-static
const koa = require('koa');
const static = require('koa-static');
let server = new koa();
server.listen(8080);
// 访问静态文件
server.use(static('www'));
在根目录创建www文件夹,并新建1.html文件,浏览器访问路径 http://localhost:8080/1.html 可访问到对应文件。
2.1访问接口:使用中间件koa-route
const koa = require('koa');
const route = require('koa-route');
let server = new koa();
server.listen(8080);
//接口 /reg?user=xxx&psw=xxx
server.use(route.get('/reg',async (ctx,next)=>{
ctx.response.body = 'hello world';
console.log(ctx.request.query);
}));
//如何获取路由参数
server.use(route.get('/catch/:user/:psw',async (ctx,username,psw,next)=>{
ctx.response.body = 'hello,' + username;
console.log(username,psw);
}));
浏览器访问路径 http://localhost:8080/reg?user=bboyjoe&psw=123456
node控制台会输出:
{user: 'bboyjoe', psw: '123456'}
浏览器访问路径 http://localhost:8080/catch/bboyjoe/123456
node控制台会输出:
bboyjoe 123456
2.2 访问接口:使用中间件koa-router
const koa = require('koa');
const router = require('koa-router');
let server = new koa();
server.listen(8080);
let r1 = router();
server.use(r1.routes());
//接口 /login?user=xxx&psw=xxx
r1.get('/login',async (ctx,next)=>{
console.log(ctx.url);
ctx.response.body='登录';
});
//接口 /reg/xxx/xxx
r1.get('/reg/:user/:psw',async (ctx,next)=>{
console.log(ctx.params);
ctx.response.body='注册';
});
浏览器访问路径 http://localhost:8080/login?user=bboyjoe&psw=123456
node控制台输出:
/login?user=bboyjoe&psw=123456
浏览器访问路径 http://localhost:8080/reg/bboyjoe/123456
node控制台输出:
{user: 'bboyjoe', psw: '123456'}
3.自己写一个访问静态文件的中间件:
现在libs文件夹下创建my-static.js
const fs = require('fs');
const assert = require('assert');
module.exports = function (root) {
assert(root,'argument root is required');
assert(typeof root === 'string', 'root must be string');
return async (ctx) => {
ctx.response.body = await new Promise((resolve,reject)=>{
fs.readFile(`${root}${ctx.request.path}`,(err,data)=>{
if(err){
reject(err);
}else{
resolve(data.toString());
}
})
})
}
}
在实际中引用my-static:
const koa = require('koa');
const myStatic = require('./libs/my-static');
let server = new koa();
server.listen(8080);
// 访问静态文件
server.use(myStatic('www'));
在根目录创建www文件夹,并新建1.html文件,浏览器访问路径 http://localhost:8080/1.html 可访问到对应文件。
4. 处理post数据:使用中间件koa-better-body来处理数据,使用koa-convert来兼容版本
<form action="http://localhost:8080/" method="post" enctype="multipart/form-data">
<input type="text" name="username"><br/>
<input type="password" name="psw"><br/>
<input type="file" name="f1"><br/>
<input type="submit" value="提交">
</form>
const koa = require('koa');
const body = require('koa-better-body');
const convert = require('koa-convert');
let server = new koa();
server.listen(8080);
server.use(convert(body({
uploadDir: './upload/',
keepExtensions: true
})));
server.use(async ctx=>{
console.log('body: ',ctx.request.body);
console.log('files: ',ctx.request.files);
console.log('fields: ',ctx.request.fields);
});
浏览器访问该表单页面,并提交数据,可以得到包含文件在内的数据。
5. cookie操作
const koa = require('koa');
let server = new koa();
server.listen(8080);
//cookie加签名
server.keys = ['jfdsakljhfgklashgkjh','iouoifoknhkjfklsdjflk','zjfjhasofjoiujofdsf'];
server.use(async ctx=>{
ctx.cookies.set('user','keven',{
maxAge: 24*3600*1000,
path: '/',
domain: 'localhost',
signed: true
});
console.log(ctx.cookies.get('user',{signed: true}));
})
浏览器访问http://localhost:8080,F12查看相应cookie信息。
6.session操作:使用中间件koa-session
const koa = require('koa');
const session = require('koa-session');
let server = new koa();
server.listen(8080);
server.keys = ['fdsajklsjalkgjlk','uioweuojlgkjsdlkj','fkljflkjeruoiu'];
server.use(session({
maxAge: 20*60*1000 //koa里默认是一天
},server));
server.use(async ctx=>{
if(!ctx.session['n']){
ctx.session['n'] = 1;
}else{
ctx.session['n']++;
}
console.log(ctx.session);
ctx.response.body = `这是你第${ctx.session['n']}次来访`;
});
浏览器访问http://localhost:8080,可在node控制台查看结果
7.mysql操作:使用中间件koa-mysql
const koa = require('koa');
const mysql = require('koa-mysql');
let server = new koa();
server.listen(8080);
const db = mysql.createPool({host:'localhost',user:'root',password:'',port:3306,database: 'an_ju_ke'});
server.use(async ctx=>{
let p = new Promise((resolve,reject)=>{
let fn = db.query('SELECT * FROM house_table');
fn(function (err,data) {
if(err){
reject(err);
}else{
resolve(data);
}
})
});
let datas = await p;
console.log(datas);
ctx.response.body = datas;
});
8.自己封装mysql中间件:
const mysql = require('koa-mysql');
module.exports = {
createPool(json){
const db = mysql.createPool(json);
let _query = db.query.bind(db);
db.query = function (sql) {
return new Promise((resolve,reject)=>{
_query(sql)((err,data)=>{
if(err){
reject(err);
}else{
resolve(data);
}
})
})
};
return db;
}
};
const koa = require('koa');
const mysql = require('./libs/koa-better-mysql');
let server = new koa();
server.listen(8080);
const db = mysql.createPool({host:'localhost',user:'root',password:'',port:3306,database: 'an_ju_ke'});
server.use(async ctx=>{
let datas = await db.query('SELECT * FROM house_table');
console.log(datas);
ctx.response.body = datas;
});
9.服务端渲染:使用中间件koa-ejs
const koa = require('koa');
const mysql = require('./libs/koa-better-mysql');
const ejs = require('koa-ejs');
let db = mysql.createPool({ host: 'localhost', user: 'root', password: '', port: '3306', database: 'an_ju_ke'});
let server = new koa();
server.listen(8080);
ejs(server,{
root: './template',
layout: false,
viewExt: 'ejs',
cache: false,
debug: true
});
server.use(async ctx=>{
let houses = await db.query('SELECT * FROM house_table');
await ctx.render('index',{
houses
})
})
在template文件夹下创建index.ejs文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ejs服务端渲染</title>
</head>
<body>
<% houses.forEach(json=>{ %>
<h4><%= json.title -%></h4>
<% }); %>
</body>
</html>
浏览器访问localhost:8080可查看效果