描述
1、Koa需要 node v7.6.0或更高版本来支持ES2015、异步方法。
2、koa搭建后端服务,模拟请求接口。
3、使用第三方路由koa-router
npm install koa-router --save
4、对于post请求,获取请求体使用第三方插件koa-body获取
npm install koa-body --save
步骤
1、新建文件夹:study-koa
2、新建package.json文件,内容如下:
{
"name": "koa2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.13.4",
"koa-router": "^10.1.1",
"supervisor": "^0.12.0"
}
}
3、新建index.js,内容如下:
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const port = process.env.PORT || 4444;
const router = new Router();
// get请求
router.get('/test-entry', async (ctx) => {
console.log('ctx===', ctx);
ctx.body = "uuuuuuuu==测试入口"
})
// post请求
router.post('/open', async (ctx) => {
console.log('ctx===', ctx);
ctx.body = "open==post请求"
})
app.use(router.routes())
app.listen(port, () => {
console.log('server listen =' + port);
})
app.on('error', err => {
log.error('server error', err)
});
4、运行
npm start
5、浏览器运行
http://localhost:4444/test-entry
6、运行结果
uuuuuuuu==测试入口
7、抽取接口文件,分模块载入。新建module文件夹,在此文件夹中新建统一出口文件entry.js,内容如下:
const Router = require('koa-router');
const router = new Router();
router.get('/test-entry', async (ctx) => {
console.log('ctx===', ctx); // =》打印语句结果展示
ctx.body = "uuuuuuuu==测试入口"
})
module.exports = router
8、在index.js中加载模块文件。接着执行第4,5步即可得到第6步的结果。
const koa = require('koa');
const Router = require('koa-router');
const app = new koa();
const port = process.env.PORT || 4444;
const router = require(./module/entry.js); // 模块文件
app.use(router.routes())
app.listen(port, () => {
console.log('server listen =' + port);
})
app.on('error', err => {
log.error('server error', err)
});
9、获取请求参数之Get请求,通过ctx.request.query获取参数内容。
router.get('/getDetail', async (ctx) => {
let day = ctx.request.query.day
if(day === null) {
ctx.body = "获取全部信息"
} else {
ctx.body = "获取第"+day+"天的信息"
}
})
http://localhost:4444/getDetail?day=1 // 获取第一天的信息
http://localhost:4444/getDetail?day=null // 获取全部信息
10、获取请求参数之Post请求,通过ctx.request.body获取参数内容。
router.post('/login', async (ctx) => {
let dto = ctx.request.body
if(dto.name === 'admin' && dto.pass === '123456') {
ctx.body = {
code: 200,
message: '登录成功',
data: {
username: 'admin',
loginTime: '2022-08-03 12:00:22'
}
}
} else {
ctx.body = {
code: 400,
message: '登录失败',
data: {}
}
}
})
11、重定向
router.get('/toBaidu', async (ctx) => {
ctx.redirect('http://www.baidu.com');
})
12、接口造值
router.post('/queryData', async (ctx) => {
let array = []
for (let index = 0; index < 10; index++) {
let obj = {
id: '(Math.floor(Math.random() * (1000 - 20)) + 1),
account: (Math.floor(Math.random() * (Math.pow(10, 8) - 20)) + 1),
name: '爱新觉罗'+index
}
array.push(obj);
}
ctx.body = {
code: 200,
message: 'ok',
data: array
}
})
13、路径带参请求并获取
router.get("/api/get/:id?", async (ctx) => {
console.log(ctx.params.id); // 2
ctx.response.body = "获取地址栏携带参数"
})
http://localhost:4444/api/get/id=2
14、跨域请求
npm install koa-cors
//index.js
const cors = require('koa-cors')
app.use(cors());
打印语句结果展示
ctx==={
request: {
method: 'GET',
url: '/test-entry2',
header: {
host: 'localhost:4444',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
cookie: 'ZX9mpgzTN2kG9nNK9o=meoyefamhh2vhmn4c2u3ensq; User_Info_Key=%7B%22UserID%22%3A%22abao%22%2C%22UserName%22%3A%22abao%22%2C%22DisplayName%22%3A%22baoge%22%7D; Curve_View_Reminder=1'
}
},
response: {
status: 404,
message: 'Not Found',
header: [Object: null prototype] {}
},
app: { subdomainOffset: 2, proxy: false, env: 'development' },
originalUrl: '/test-entry2',
req: '<original node req>',
res: '<original node res>',
socket: '<original node socket>'
}