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

前端开发 作者: 2024-08-22 22:45:01
在Java的Spring框架中,我们经常会看到类似于`@Controller`这样的注解,这类代码能够极大的提高我们代码的可读性和复用性。而在Javascript的ES7提案中,有一种新的语法叫做de

创建package.json

{
  "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并编写代码

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');
});
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');
});
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');
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');
});
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66911.html