代码拉取完成,页面将自动刷新
同步操作将从 fyl080801/egg-decorator-router 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
使用装饰器来定义 egg.js 的路由和中间件
egg-decorator-router 版本 | egg 1.x |
---|---|
1.x | 😁 |
0.x | ❌ |
// config/plugin.js
exports.decoratorRouter = {
enable: true,
package: 'egg-decorator-router'
}
基于 typescript 的 eggjs 项目可直接使用装饰器
如果是 js 项目,则需要手动安装babel-plugin-transform-decorators-legacy
和babel-plugin-transform-object-rest-spread
这两个包,并在项目里加入.babelrc
文件
.babelrc 定义如下:
{
"plugins": ["transform-decorators-legacy", "transform-object-rest-spread"]
}
Http 请求的完整路径是根路径和子路径合并的结果
在 controller 中先引入依赖
const {
Route,
HttpAll,
HttpGet,
HttpPost,
HttpPut,
HttpPatch,
HttpDelete,
Middleware
} = require('egg-decorator-router')
如果使用 typescript
import {
Route,
HttpAll,
HttpGet,
HttpPost,
HttpPut,
HttpPatch,
HttpDelete,
Middleware
} from 'egg-decorator-router'
在 controller 里定义一个根路径
// root path is '/'
@Route()
// root path is '/'
@Route('/')
// root path is '/routename'
@Route('/routename')
// root path is '/routename/action'
@Route('/routename/action')
支持定义参数
@Route('/routename/:name')
支持 Http 方法 HttpGet
HttpPost
HttpPut
HttpPatch
HttpDelete
HttpAll
在 controller 方法上定义子目录
// sub-path is '/'
@HttpGet()
// sub-path is '/'
@HttpGet('/')
// sub-path is '/action'
@HttpGet('/action')
// sub-path is '/action/:id'
@HttpGet('/action/:id')
@Middleware(routeM)
'use strict'
const { Controller } = require('egg')
const { Route, HttpGet, Middleware, filters } = require('egg-decorator-router')
const { DefaultFilter } = filters
const routeM = (ctx, next) => {
console.log('passed route middleware')
next()
}
const actionM = i => {
return (ctx, next) => {
console.log('passed action middleware ' + i)
next()
}
}
@Route()
@Middleware(routeM)
class HomeController extends Controller {
@HttpGet('/') // path: /
async index() {
await new Promise(resolve => {
this.ctx.body = 'ssss'
resolve()
})
}
@HttpGet() // path: /func1
@Middleware(actionM(2), 2)
@Middleware(actionM(1), 1)
func1(ctx) {
ctx.body = 'hi, func1'
}
@HttpGet('/:id') // path: /:id
@DefaultFilter('aaa')
func2(ctx) {
ctx.body = 'hi, func2 ' + ctx.params.id
}
}
module.exports = HomeController
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。