安装环境
安装Node与npm
安装Node.js
brew install node@8
安装指定版本的npm
npm install npm@5.6.0 -g
检查Node版本
node -v
检查npm版本
npm -v
升级Node
npm install -g n
一、Koa
- 安装Koa
新建一个项目koademo
,打开终端
mkdir koademo cd koademo npm init
此时会要求输入一些配置信息,什么都不用写,一直回车
此时项目路径下会新增文件package.json
安装koa
npm install koa
新建index.js
文件,添加如下代码,开启服务,监听端口3000
const Koa = require("koa");
const app = new Koa();
//开启服务,监听端口3000
app.listen(3000);
new Koa():创建的对象被称为
Koa
应用对象。应用对象时带有node http
服务的Koa接口,它可以处理中间件的注册,将http
请求分发到中间件,进行默认错误处理,以及对上下文,请求和响应对象进行配置。 app.listen(3000):用于启动一个服务的快捷方法,是对http.createServer
的简单包装,它实际上这样运行:http:createServer(app.callback()).listen(3000)
;
context
context
是一个请求的上下文,该对象封装了一个传入的http
消息,context
有request
和response
属性,我们可以设置两个属性来处理和响应不同的请求。
- 代码
const Koa = require("koa");
const app = new Koa();
//开启服务,监听端口3000
app.use((ctx,next)=>{
ctx.response.body="hello world";
});
app.listen(3000);
- 说明
app.use(function):将给定的function当做中间件加载到应用中。 ctx:每一个请求都会创建一段上下文,在控制业务逻辑的中间件中,上下文被寄存在
ctx
对象中。为了使用方便,许多上下文属性和方法都被委托代理到他们的ctx.request
和ctx.response
,比如访问ctx.type
和ctx.length
将被代理到response
对象,ctx.path
和ctx.method
将被代理到request
对象。
- 启动服务
node index.js
浏览器访问 http://localhost:3000
,如果运行正确,在页面会显示hello world
。
三、网页模板
实际开发中,返回给用户的网页往往都写成模板文件。我们可以让Koa
先读取模板文件,然后将这个模板返回给用户。
- 代码
const Koa = require("koa");
const app = new Koa();
const fs = require("fs");
app.use((ctx,next)=>{
//必须指定type,否则调用fs模板后默认响应类型为为`application/octet-stream`类型
ctx.response.type="text/html";
//将文件作为响应体流失传输
ctx.response.body=fs.createReadStream("./views/index.html");
});
app.listen("3000");
四、中间件
Koa
所有的功能都是通过中间件实现的。中间件处在HTTP Request
和HTTP Response
中间
Koa
的中间件之间按照编码顺序在栈内一次执行,允许您执行操作并向下传递请求,之后过滤并逆序返回响应。
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx,next)=>{
console.log("first");
await next();
console.log("first over")
});
app.use(async(ctx,next)=>{
console.log("second");
await next();
console.log("second over")
});
app.use(async(ctx,next)=>{
console.log("third");
await next();
console.log("third over");
});
有
async
标记的函数称为异步函数,在异步函数中,可以用await
调用另一个异步函数。使用await
时,它所在的方法必须使用关键字async。
执行结果:
first
second
third
third over
second over
first over
五、原生路由
开发中需要根据用户请求返回相应的数据,可以通过设置路由实现
- 代码
const Koa = require("koa");
const app = new Koa();
app.use(async (ctx)=>{
if (ctx.request.path=="/"){
ctx.response.body = "首页";
}
switch (ctx.request.path){
case "/":{
ctx.response.body = "首页";
break;
}
case "/login":{
ctx.body = "login";
break;
}
case "/test":{
ctx.body = "test";
break;
}
}
});
//开启服务,监听端口3000
app.listen(3000);
浏览器访问 | 结果 |
---|---|
http://localhost:3000/ | 首页 |
http://localhost:3000/login | login |
http://localhost:3000/test | test |
六、koa-router
原生路由用起来不方便,我们可以使用封装好的koa-router模块
npm install koa-router
- 代码
const Koa = require("koa");
const app = new Koa();
const r = require("koa-router");
const router = r();
//设置路由
router.get("/",(ctx,next)=>{
ctx.body = "首页";
});
router.get("/login",(ctx,next)=>{
ctx.body = "login";
});
router.get("/test",(ctx,next)=>{
ctx.body = "test";
});
//绑定路由
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
七、重定向
将上面的代码中test
重定向到login
const Koa = require("koa");
const app = new Koa();
const r = require("koa-router");
const router = r();
//设置路由
router.get("/",(ctx,next)=>{
ctx.body = "首页";
});
router.get("/login",(ctx,next)=>{
ctx.body = "login";
});
//test重定向到login
router.get("/test",(ctx,next)=>{
ctx.response.redirect("/login");
});
//绑定路由
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
八、获取get请求参数
/**
* Created by zhqmac on 2018/7/22.
*/
const Koa = require("koa");
const app = new Koa();
const router= require("koa-router")();
app.use((ctx,next)=>{
console.log(ctx.request.method);
console.log(ctx.request.url);
next()
});
//http://localhost:3000/login?name=zhq?age=26
router.get("/login",ctx=>{
var name = ctx.query.name;
var age = ctx.query.age;
console.log(name+"年龄:"+age);
ctx.body = `<h1> Hello,${name}</h1>`
});
//http://localhost:3000/regist/zhq/26
router.get("/regist/:name/:age",ctx=>{
var name = ctx.params.name;
var age = ctx.params.age;
ctx.response.body = `<h1>regist, ${name} ${age}!</h1>`;
});
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
获取post请求参数
const Koa = require("koa");
const app = new Koa();
const koaBody = require("koa-body");
const router= require("koa-router")();
app.use(async (ctx,next)=>{
console.log(ctx.request.method);
console.log(ctx.request.url);
await next()
});
router.post("/login", (ctx,next) => {
var body = ctx.request.body;
console.log(body);
console.log(body.name);
ctx.body = {name:body.name};
});
app.use(koaBody());
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
使用curl
发起post请求
curl -X POST –data “name=zhq” 127.0.0.1:3000/login
返回结果是一个json串
{
"name": "zhq"
}
十、加载静态资源
如图片、字体、样式表、脚本等
引入koa-static
npm install koa-static
下面以加载一张图片为例
-
新建目录
static
-
在
static
目录下新建images
目录 -
在
images
目录下添加一张图片avatar.JPG
- 代码
const Koa = require("koa");
const app = new Koa();
const path = require("path");
const koaStatic= require("koa-static");
const router= require("koa-router")();
//静态资源目录对于相对入口文件的路径
const staticPath = './static';
router.get("/",ctx=>{
ctx.body = "<html><a href='/images/avatar.JPG'>点我</a></html>"
});
app.use(koaStatic(
path.join(__dirname,staticPath)
));
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
十一、模板引擎
安装ejs模板引擎
npm install ejs npm install koa-views
- 代码
const Koa = require("koa");
const app = new Koa();
//引入koa-router的时候要加上一个()
var router = require("koa-router")();
var views = require("koa-views");
var path = require("path");
//views 必须是异步才可以
router.get("/login",async ctx=>{
//将json里面的值替换为文件里面的变量
//go 里面使用的是template模板,他们功能类型
var name = "zhq";
await ctx.render("loginEjs.ejs",{
name
})
});
router.get("/regist",async ctx=>{
await ctx.render("regist.html")
});
app.use(views(
path.join(__dirname,"./views"),
{
extensions:"ejs",
//默认去views下面获取ejs后缀的文件
//如果是其他类型的文件需要制定文件类型
map:{
html:"ejs"
}
}
));
//路由注册到中间件
app.use(router.routes());
//开启服务,监听端口3000
app.listen(3000);
loginEjs.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
background: darkcyan;
}
</style>
</head>
<body>
<div>注册 <%= name %></div>
</body>
</html>