在express中使用ES7装饰器构建路由
在Java的Spring框架中,我们经常会看到类似于@Controller这样的注解,这类代码能够极大的提高我们代码的可读性和复用性。而在Javascript的ES7提案中,有一种新的语法叫做decorator,它能够在Javascript中实现与注解相同的功能。
@tuzilow/express-decorator
@tuzilow/express-decorator是由本人开发的一个简单的express装饰器包,具有@Controller、@RootUrl、@Get等API,能够方便快捷的构建express后台接口。
正式开始
创建package.json
执行npm init,并使用npm或yarn添加以下依赖
{
"name": "decorator-demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@tuzilow/express-decorator": "^0.0.3",
"express": "^4.17.1"
},
"devDependencies": {
"@babel/cli": "^7.11.6",
"@babel/core": "^7.0.0",
"@babel/node": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/plugin-proposal-decorators": "^7.10.5",
"@babel/preset-env": "^7.0.0",
"babel-eslint": "^9.0.0"
},
"scripts": {
"start": "babel-node index"
}
}
创建.babelrc
{
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
],
"presets": ["@babel/preset-env"]
}
创建index.js并编写代码
首先,编写一个普通的express应用
import express from 'express';
const Server = express();
Server.get('/', (req, res) => {
res.json({
title: 'hello world',
});
});
Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});
执行无误后使用@tuzilow/express-decorator对其进行改造
import express from 'express';
import { Controller, Get } from '@tuzilow/express-decorator';
const Server = express();
@Controller
class User {
@Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
}
}
Server.use(new User());
Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});
运行结果与前面普通的express应用的运行结果相同,如果想要设定统一的父级路由,可以使用@RootUrl
import express from 'express';
import { Controller, Get, RootUrl } from '@tuzilow/express-decorator';
const Server = express();
@Controller
class User {
@RootUrl('/user') url() {}
@Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
}
@Get('/list')
list(req, res) {
res.json({
title: 'this is a list',
});
}
}
Server.use(new User());
Server.listen(3000, () => {
console.info('running in http://localhost:3000');
这样请求路径就会变为http://localhost:3000/user和http://localhost:3000/user/list,因为该装饰器包只提供了简易的API,因此传递参数、设置header等操作需要使用express的方法
import express from 'express';
import { Controller, Get, RootUrl, Post } from '@tuzilow/express-decorator';
const Server = express();
@Controller
class User {
@RootUrl('/user') url() {}
@Get('/')
home(req, res) {
res.json({
title: 'hello world',
});
}
// query传参
@Get('/getOne')
getOne(req, res) {
const { id } = req.query;
res.json({
title: 'hello world',
id,
});
}
// params传参
@Get('/list/:id')
getItem(req, res) {
const { id } = req.params;
res.json({
title: 'hello world',
id,
});
}
// body传参
@Post('/create')
create(req, res) {
const { id } = req.body;
res.json({
code: 0,
id,
});
}
}
Server.use(new User());
Server.listen(3000, () => {
console.info('running in http://localhost:3000');
});
项目源码
- GitHub仓库地址:Tuzilow/express-decorator
- npm地址:@tuzilow/express-decorator
在express中使用ES7装饰器构建路由的更多相关文章
- Python中利用函数装饰器实现备忘功能
Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下 " ...
- Angular 个人深究(一)【Angular中的Typescript 装饰器】
Angular 个人深究[Angular中的Typescript 装饰器] 最近进入一个新的前端项目,为了能够更好地了解Angular框架,想到要研究底层代码. 注:本人前端小白一枚,文章旨在记录自己 ...
- python 中多个装饰器的执行顺序
python 中多个装饰器的执行顺序: def wrapper1(f1): print('in wrapper1') def inner1(*args,**kwargs): print('in inn ...
- 第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析
第7.17节 Python类中的静态方法装饰器staticmethod 定义的静态方法深入剖析 静态方法也是通过类定义的一种方法,一般将不需要访问类属性但是类需要具有的一些能力可以静态方法提供. 一 ...
- 第7.26节 Python中的@property装饰器定义属性访问方法getter、setter、deleter 详解
第7.26节 Python中的@property装饰器定义属性访问方法getter.setter.deleter 详解 一. 引言 Python中的装饰器在前面接触过,老猿还没有深入展开介绍装饰 ...
- ts装饰器的用法,基于express创建Controller等装饰器
TS TypeScript 是一种由微软开发的自由和开源的编程语言.它是 JavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类 型和基于类的面向对象编程. TypeScript 扩 ...
- EntityFramework中使用Repository装饰器
铺垫 通常在使用 EntityFramework 时,我们会封装出 IRepository 和 IUnitOfWork 接口,前者负责 CRUD 操作,后者负责数据提交 Commit. public ...
- nodejs+express中设置登录拦截器
在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...
- Python中的各种装饰器详解
Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...
随机推荐
- 文章要保存为TXT文件,其中的图片要怎么办?Python帮你解决
前言 用 python 爬取你喜欢的 CSDN 的原创文章,保存为TXT文件,不仅查看不方便,而且还无法保存文章中的代码和图片. 今天教你制作成 PDF 慢慢看.万一作者的突然把号给删了,也会保存备份 ...
- Xor 思维题
Xor 思维题 题目描述 小\(Q\)与小\(T\)正在玩一棵树.这棵树有\(n\)个节点,编号为 \(1\),\(2\) \(3...n\),由\(n-1\)条边连接,每个节点有一个权值\(w_i\ ...
- 坚持第一天:HashMap和Hashtable的区别
其实,到底是用HashMap和Hashtable主要看需求, 1.它们俩都共同实现了:Map接口,但是Hashtable实现是基于Dictionary抽象类的,在java5的时候提供了Concurre ...
- mac 安卓生成证书(uniapp项目安卓证书申请)
mac 安卓生成证书 义务需求: 最近在开发基于uniapp框架的app,到了打包发布的阶段,来尝试打包为安卓的apk安装包.在用HBuild打包的时候需要提供安卓的数字证书(.keystore 文 ...
- VS2005 如何打开VS2008的工程 2009-06-24 20:22
大家都碰到过用2005打开2008的工程吧.2008打开2005是没有问题,但是反过来呢,却不可以.当用2005打开2008时,看着工具提示要进行工程转换心里高兴吧,当转换后发现工程无法加载是不是很居 ...
- SpringSecurity权限管理系统实战—一、项目简介和开发环境准备
目录 SpringSecurity权限管理系统实战-一.项目简介和开发环境准备 SpringSecurity权限管理系统实战-二.日志.接口文档等实现 SpringSecurity权限管理系统实战-三 ...
- Lambda表达式的几种实现过程
1.无参数+语句(代码块):适用于匿名内部类中方法无参数的情况 private void threadTest(){ //普通写法 new Thread(new Runnable(){ @Overri ...
- 国人开源了一款超好用的 Redis 客户端,真香!!
大家都知道,Redis Desktop Manager 是一款非常好用的 Redis 可视化客户端工具,但可惜的是 v0.9.4 版本之后需要收费了: 这个工具不再免费提供安装包了,要对所有安装包收费 ...
- 初识ABP vNext(4):vue用户登录&菜单权限
Tips:本篇已加入系列文章阅读目录,可点击查看更多相关文章. 目录 前言 开始 登录 菜单权限 运行测试 最后 前言 上一篇已经创建好了前后端项目,本篇开始编码部分. 开始 几乎所有的系统都绕不开登 ...
- centos7 重装ssh服务
重装之前先要卸载之前安装的无法 通过rpm命令查看openssh的安装情况 rpm -qa openssh* 通过yum remove命令卸载 yum remove openssh* 重装: yum ...