直接使用框架:
- npm init
- npm install koa
- 新建app.js:
const Application = require('koa');
const Koa = require('koa');
const app = new Koa();
app.listen(8085);
app.use((ctx) => {
ctx.body = "hello koa!!"
})
- 启动:
node app.js - 访问:
http://localhost:3000
使用脚手架:
- 安装:
npm install -g koa-generator
koa2 --version
- 创建项目:
koa2 projectName
cd projectName
npm install
npm run dev
如果报 '.'不是内部或外部命令
进入到项目下的node_modules/.bin,执行 npm link nodemon,修改 package.json里scripts的dev的值为:nodemon bin/www
- 访问:
http://localhost:3000 - routes文件夹下新建demo.js:
const router = require('koa-router')();
router.prefix('/demo')
router.get('/',function (ctx) {
const query = ctx.query;
console.log('query:',query);
ctx.body = "get function data";
})
router.post('/',function (ctx) {
const reqBody = ctx.request.body
console.log('request body:',reqBody);
ctx.body = "post function data"
// ctx.body = {
// code:200,
// success:true,
// data:'post function data'
// }
})
module.exports = router
- app.js增加:
//引入路由
const demo = require('./routes/demo');
//注册路由
app.use(demo.routes(),demo.allowedMethods())
网友评论