必备知识
- node.js基础(菜鸟教程)
- nodejs框架-express
- nodejs框架-koa(本文)
- vue基础(后期会封装基于vuerouter的路由)
nodejs框架-koa
1. 中文文档地址:https://koa.bootcss.com/
2. node模块仓库地址:https://www.npmjs.com/
开始学习
- 学习一种语言 (从hello world 开始)
- 建一个文件夹 初始化package.json (npm init --yes)
- 创建一个简单的koa应用(hello world)
- 安装koa模块 npm install koa --save 并且在根目录创建app.js文件 代码如下:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);//监听localhost:3000
- 执行node app.js
- 打开浏览器 : http://localhost:3000
服务器自动重新部署
由于每次更新都需要重启服务,这显然不方便,我们希望修改了文件服务能自动重启.nodemon能实现这样功能
1. 全局安装npm i nodemon -g
2. 启动服务的时候用nodemon app.js 代替node app.js
3. 也可以在package.json里面重新设置 代码如下:
"scripts": {
"start": "nodemon app.js"
},//启动项目就 npm start 就行了
koa路由篇(koa-router)
- 安装koa-router
npm i koa-router --save-dev
- app.js,代码如下
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router();
router.get('/', ctx => {
ctx.body = 'hello world'
})
router.get('/demo1', ctx => {
ctx.body = 'demo1'
})//get请求
router.post('/demo1', ctx => {
ctx.body = 'demo1'
})//post请求
router.all('/demo2', ctx => {
ctx.body = 'demo2'
})//router.all表示两种方式都支持
app.use(router.routes());
app.listen(3000, () => {
console.log('服务已启动,在 http://localhost:3000/');
});
- 启动服务即可看到效果 http://localhost:3000/
- 如果一直在app.js里面写路由 这显然不合理 ,我们一般会把router单独放到一个文件,然后倒入到app.js使用 如图:
- 单个模块的路由 js
const Router = require('koa-router')
const cityRouter = new Router(
{
prefix: "/city" //配置父路由
}
);
cityRouter.all('/add', ctx => {
ctx.body = '城市增加'
})
cityRouter.all('/getList', ctx => {
ctx.body = '城市获取列表数据'
})
cityRouter.all('/del', ctx => {
ctx.body = '城市删除'
})
cityRouter.all('/edit', ctx => {
ctx.body = '城市编辑'
})
module.exports = cityRouter;
- router/index.js 的代码:
const cityRouter = require('./city')
//const filmRouter = require('./film')
...
//导出一个方法 然后在app.js里面使用 初级封装=>后面会模仿vue的路由封装到底
function initRouter(app) {
app.use(cityRouter.routes());
// app.use(filmRouter.routes());
...
}
module.exports = initRouter
- app.js里面的代码为:
const Koa = require('koa')
const app = new Koa()
const initRouter = require("./router/index")
//路由
initRouter(app)
app.listen(3000, () => {
console.log('服务已启动,在 http://localhost:3000/');
});
koa中间件
一个请求从发出到返回数据,如果我们想在这个过程里做一些统一的操作,可以使用中间件来完成.
- 中间件是个函数
- 使用中间件的方式, app.use(中间件)
app.use((ctx, next) => {
// 在ctx上放入username,后面的所有请求的ctx里都会有username这个变量
ctx.username = '我是Mr.He';
// 处理完之后放行,不使用next()的话,程序会被挂起来不动了
next(); // 在vue路由守卫里曾使用过next
})
- 中间件有顺序(重点踩坑!!!)
配置koa静态资源目录
- 在目录中创建目录public,在创建public下创建文件demo.html,访问http://localhost:3000/public/demo.html是无法访问得到,因为我们还没有设置静态资源目录,设置静态资源目录要用到koa-static模块
- 安装koa-static
npm i koa-static --save-dev
- 在app.j是里加入如下代码 (注意在路由前面):
const koaStatic = require('koa-static');
app.use(koaStatic(__dirname + '/public'));
- 再来访问 http://localhost:3000/demo.html 就可以访问了,ps: 路径不用加public
获取请求参数
- 给刚才的demo.html添加axios用来发送get请求,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
</head>
<body>
<h3>
测试koa静态资源目录
</h3>
<script>
let url = 'http://localhost:3000/city/add';
let data = {
params: {
username: 'Mr.He',
phone: 13800000000
}
}
axios.get(url, data).then(res => {
console.log(res);
})
</script>
</body>
</html>
- router/city.js的代码如下:
cityRouter.all('/add', ctx => {//.all表示什么请求方式都行(get,post...)
//获取请求参数
const username = ctx.query.username;
const phone = ctx.query.phone;
ctx.body = { //返回
module: 'add',
username,
phone
}
})
- post请求有些不一样 获取post请求
- 获取post请求需要使用koa-body模块
- 安装koa-body npm i koa-body --save
npm i koa-body --save
- 在app.js里加入如下代码:
const koaBody = require('koa-body'); app.use(koaBody());
- 获取post请求参数的代码如下:
ctx.request.body.xxx
- 使用中间件封装请求参数
// 把get请求参数和post请求参数都放入params对象
app.use((ctx, next) => {
ctx.params = {
...ctx.query,
...ctx.request.body
}
next();
});
跨域配置
- 自己编写一个中间件即可,代码如下:
app.use((ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*");
ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
// 请求头设置
ctx.set(
"Access-Control-Allow-Headers",
`Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild,x-token,sessionToken,token`
);
if (ctx.method == "OPTIONS") {
ctx.body = 200;
} else {
next();
}
})
- 访问刚才的demo.html文件, http://localhost:3000/demo.html, 你会发现你的请求的响应头上添加了Access-Control-Allow-Origin: *,说明服务器跨域设置已经成功了.