正儿八经的前端开发迈出全栈的第一步,记录一次用 koa2 搭建一个后台应用。html
前期已安装好前端
# 建立项目文件夹
mkdir node-koa2-app
# 进入文件夹
cd node-koa2-app
# npm 初始化
npm init -y
复制代码
安装koa框架node
npm i koa -S
复制代码
建立 app.js 文件,尝试下 Hello World!npm
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World!';
});
app.listen(3000);
复制代码
访问 http://localhost:3000
就能看到 Hello World!
了,真是简单。bash
再次优化一下,访问是一个完成的 html
app
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello World!</h1>';
});
app.listen(3000, () => {
console.log('listening server http://localhost:3000');
});
app.listen(3001, () => {
console.log('listening server http://localhost:3001');
});
复制代码
Koa 应用程序是一个包含一组中间件函数的对象,它是按照相似堆栈的方式组织和执行的。框架
ctx就是上下文(Context),Context 将 node 的 request 和 response 对象封装到单个对象中,还对 Koa 内部对一些经常使用的属性或者方法作了代理操做,使得咱们能够直接经过 ctx 获取。好比,ctx.request.url 能够写成 ctx.url。除此以外,Koa 还约定了一个中间件的存储空间 ctx.state。经过 state 能够存储一些数据,好比用户数据,版本信息等。koa
这是一种级联的方式,当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开而且每一个中间件恢复执行其上游行为。async
// 按照官方示例
const Koa = require('koa')
const app = new Koa()
// 记录执行的时间
app.use(async (ctx, next) => {
let stime = new Date().getTime()
console.log('开始时间'+stime);
await next()
let etime = new Date().getTime()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World!</h1>'
console.log('结束时间'+etime);
console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`)
});
app.use(async (ctx, next) => {
console.log('中间件1 doSoming');
await next();
console.log('中间件1 end');
})
app.use(async (ctx, next) => {
console.log('中间件2 doSoming');
await next();
console.log('中间件2 end');
})
app.use(async (ctx, next) => {
console.log('中间件3 doSoming');
await next();
console.log('中间件3 end');
})
app.listen(3000, () => {
console.log('server is running at http://localhost:3000')
})
复制代码
引入koa-router函数
npm i koa-router -S
复制代码
安装完成后执行
const Koa = require('koa')
// 注意 require('koa-router') 返回的是函数:
const router = require('koa-router')()
const app = new Koa()
// 添加路由
router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>index page</h1>`
})
router.get('/home', async (ctx, next) => {
ctx.response.body = '<h1>HOME page</h1>'
})
router.get('/404', async (ctx, next) => {
ctx.response.body = '<h1>404 Not Found</h1>'
})
// 调用路由中间件
app.use(router.routes())
app.listen(3000, ()=>{
console.log('server is running at http://localhost:3000')
})
复制代码
这样就能实现一个网站应用了,对于前端开发者来讲,node 有自然的优点,js语法至关友好,固然确定也会由于弱语言类型少不了坑,后面一步一步学习。