We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
安装koa2
koa2
安装koa-router koa-router 提供了 .get、.post、.put 和 .del 接口来处理各种请求
koa-router
这里按照MVC的思想来组织代码结构:
MVC
server ├── app.js ├── controller ├── middleware ├── package.json ├── package-lock.json └── router
hello world
index.js
module.exports = { hello: async (ctx, next) => { ctx.response.body = 'Hello World' } }
const logger = () => { return async (ctx, next) => { const start = Date.now() await next() const responseTime = (Date.now() - start) console.log(`响应时间为: ${responseTime / 1000}s`) } } module.exports = (app) => { app.use(logger()) }
注意,中间件只能是函数。
const router = require('koa-router')() module.exports = app => { router.get('/', Controller.hello) // 注意是在controller编写的hello函数 app.use(router.routes()).use(router.allowedMethods()) }
const koa = require('koa') const app = new koa() const middleWare = require('./middleware') const router = require('./router') middleWare(app) router(app) app.listen(port, () => { console.log('server is running at http://localhost:3000') })
node app.js
http://localhost:3000
Hello World
至此,使用koa2编写接口的基本思路就说完了,一般都是在controller对数据库进行CRUD,然后配置相关路由,就完成了一个接口服务的开发。
controller
CRUD
The text was updated successfully, but these errors were encountered:
No branches or pull requests
依赖安装
安装
koa2
安装
koa-router
koa-router 提供了 .get、.post、.put 和 .del 接口来处理各种请求
代码分层
这里按照
MVC
的思想来组织代码结构:编码
当然还是经典的
hello world
。在 controller 文件下新建index.js
,写入以下代码:增加一个中间件来记录响应时间,在 middleware 文件下新建
index.js
,写入以下代码:注意,中间件只能是函数。
增加一个路由来试试,在 router 文件下新建
index.js
,写入以下代码:node app.js
然后打开浏览器,访问http://localhost:3000
就可以看到Hello World
了。总结
至此,使用
koa2
编写接口的基本思路就说完了,一般都是在controller
对数据库进行CRUD
,然后配置相关路由,就完成了一个接口服务的开发。The text was updated successfully, but these errors were encountered: