在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.被装饰对象无参数: ...
随机推荐
- C#算法设计排序篇之03-直接插入排序(附带动画演示程序)
直接插入排序(Straight Insertion Sort) 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/679 访 ...
- Golang 简单爬虫实现,爬取小说
为什么要使用Go写爬虫呢? 对于我而言,这仅仅是练习Golang的一种方式. 所以,我没有使用爬虫框架,虽然其很高效. 为什么我要写这篇文章? 将我在写爬虫时找到资料做一个总结,希望对于想使用Gola ...
- Kafka 为什么快
Kafka 为什么能那么快 | Kafka高效读写数据的原因 无论 kafka 作为 MQ 也好,作为存储层也罢,无非就是两个功能(好简单的样子),一是 Producer 生产的数据存到 broker ...
- 初始化vtable
在InstanceKlass::link_class_impl()方法中完成方法连接后会继续初始化vtable与itable,之前已经介绍过vtable与itable,并且在类解析过程中已经完成了大小 ...
- 学长小清新题表之UOJ 31.猪猪侠再战括号序列
学长小清新题表之UOJ 31.猪猪侠再战括号序列 题目描述 大家好我是来自百度贴吧的_叫我猪猪侠,英文名叫\(\_CallMeGGBond\). 我不曾上过大学,但这不影响我对离散数学.复杂性分析等领 ...
- Windows下make clean指令错误[错误码2](系统找不到指定文件)的解决方案
问题来源 因为笔者想用GCC编译器进行Windows下的C语言编程,安装了Mingw-w64的x86_64-posix-seh版本,并按照Visual Studio Code官方的教程,将Mingw- ...
- nova 通过 python curl 创建虚拟机---keystone v2
#! /bin/python #coding=utf- import urllib2 import json import requests # token post_url = 'http://12 ...
- xfs文件系统修复方法
1. 前言首先尝试mount和umount文件系统,以便重放日志,修复文件系统,如果不行,再进行如下操作.fdisk -l 查看硬盘分区情况mount -l 查看文件系统挂载情况df -h 查看文件系 ...
- Matplotlib&Numpy
Matplotlib 是专门用于开发2D图表(包括3D图表) 以渐进.交互式方式实现数据可视化 实现一个简单的Matplotlib画图 ①导入:matplotlib.pytplot包含了一系列类似于m ...
- 第3篇 Scrum 冲刺博客(专✌️团队)
目录 一.站立式会议 1.1 会议照片 1.2 成员完成情况 二.项目燃尽图 三.成员代码/文档签入记录 3.1 代码签入 3.2 Issue链接 3.3 CodeReview代码规范文档 四.最新项 ...