在express中使用ES7装饰器构建路由

前端之家收集整理的这篇文章主要介绍了在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,并使用npmyarn添加以下依赖

{
  "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,});
  }
   
  @Get('/list')
  list(req,res) {
    res.json({
      title: 'this is a list',() => {
  console.info('running in http://localhost:3000');

这样请求路径就会变为http://localhost:3000/userhttp://localhost:3000/user/list,因为该装饰器包只提供了简易的API,因此传递参数、设置header等操作需要使用express的方法

import express from 'express';
import { Controller,RootUrl,Post } from '@tuzilow/express-decorator';

const Server = express();

@Controller
class User {
  @RootUrl('/user') url() {}

  @Get('/')
  home(req,});
  }

  // 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',});
  }

  // body传参
  @Post('/create')
  create(req,res) {
    const { id } = req.body;
    res.json({
      code: 0,() => {
  console.info('running in http://localhost:3000');
});

项目源码

原文链接:https://www.f2er.com/js/991608.html

猜你在找的JavaScript相关文章