带有 ExpressJS 路由器的 CRUD

CRUD with ExpressJS router

我是 MEAN 堆栈的新手,我正在尝试找出处理路由的最佳方法,express.Router() 或 AngularJS 的控制器 (https://docs.angularjs.org/tutorial/step_07) .

我正在使用 Express v4.12.0、Angular v1.3.13、EJS v1(用于模板)。

我真的很喜欢 Express 路由 (/items/itemId) 中 URL 的干净程度,我不太喜欢 Angular,因为它在URL (/items#/items/itemId).

现在我只有一个页面列出了我的项目 (players.ejs):

<!DOCTYPE html>
<html lang="en" ng-app='app'>
<head>
    <title>Fantasy Football Helper | <%- title %></title>
    <% include partials/head %>
    <script type="text/javascript" src="/javascript/app/playersApp.js"></script>
</head>
<body class="container">

    <% include partials/header %>

    <main>
        <div class="row">
            <div class="col-sm-8">

                <h2>Fantasy Players</h2>

                <div ng-controller="PlayerController">
                    <div class="player" ng-repeat="player in players">
                        <p>
                            <a href="/players/{{ player._id }}"><strong>{{ player.name }} - {{ player.position }} - {{ player.team }}</strong></a>
                        </p>
                    </div>
                </div>
                <!-- Ideally, other CRUD UI goes here -->

            </div>

            <% include partials/sidebar %>
        </div>
    </main>

    <footer>
        <% include partials/footer %>
    </footer>

</body>
</html>

我想为这些 players 的每个 CRUD 操作重用这个 players.ejs 模板。目前我正在使用 Express 的路由。我的主要 app.js:

中有以下路线
var players = require('./routes/players');
app.use('/players', players);

我在 players 路线 (routes/players.js) 中有以下路线:

var express = require('express');
var router = express.Router();

/* GET /players listing. */
router.get('/', function(req, res, next) {
    res.render('players', { title: 'Players'});
});

/* GET /player details. */
router.get('/:id', function(req, res, next) {
    res.render('players', { title: 'Fantasy Players'});
});

module.exports = router;

有没有办法,使用 Express 的路由,让一个 EJS 模板根据 http 操作提供不同的部分?

注意:我一直在参考以下指南:

您可以将布尔值传递给您的模板:

router.get('/', function(req, res, next) {
    res.render('players', { title: 'Players', foo: true});
});

router.get('/:id', function(req, res, next) {
    res.render('players', { title: 'Fantasy Players', foo: false});
});

并根据布尔值呈现不同的部分:

<%if (foo) { %>
 <% include partials/foo %>
<% } else { %>
  <% include partials/bar %>
<% } %>

我相信有很多方法可以解决这个问题。我可以告诉你什么对我有用,我从 pluralsight 那里采用的方法。

让您的所有快递路线都服务于同一个 index.ejs 文件:

app.get('/', function(req, res, next) {  
 res.render('index.ejs',{
   page: 'home'
 });
}); 

app.get('/about', function(req, res, next) {  
 res.render('index.ejs',{
       page: 'about'
     });
    }); 

app.get('/about/:id', function(req, res, next) {
 res.render('index.ejs',{
       page: 'about'
     });
    }); 

我的 index.ejs 大部分都被导航 ng-view 和页脚精简了。

我的快速路由处理 http 请求的所有服务器逻辑:

router.get('/abo', aboutController.list);
router.post('/abo', aboutController.create);
router.route('/abo/:_id')
    .get(function(req, res) {
        About.findById(req.params._id, function(err, result) {
            if (err)
                res.send(err);
            res.json(result);
        });
    })
.put(function(req, res) {
        About.findById(req.params._id, function(err, abo) {
            if (err)
                res.send(err);
            abo.title = req.body.title;     // update the items info
            abo.shortname = req.body.shortname;
            abo.contents = req.body.contents;
            // save the items
            abo.save(function(err) {
                if (err)
                    res.send(err);
                res.json({ message: 'About content updated!' });
            });
        });
    })
.delete(function(req, res) {
        About.remove({
            _id: req.params._id
        }, function(err, service) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

Angular 匹配快速 url 路线:

.when('/', {
        templateUrl: 'templates/home.html',
        controller:'homeController'

    })
.when('/about/:id', {
        templateUrl: 'templates/template.html',
        controller: 'refactoredController'
    })

我也在用:

$locationProvider.html5Mode(true);

这允许干净的 urls 没有 #

我的 angular 控制器与我为 http 调用设置的 angular 服务对话,该服务将数据传递到后端(express),由路由接管。

function getByID(shortname, api) { 
return $http({
  method: 'GET',
  url: '/api/' + api,
  shortname: shortname
})
.then(getVolunteerByIDSuccess)
.catch(sendGetVolunteerError);

} 

function updateItem(data, api) {
  console.log(data);
  return $http({
    method: 'PUT',
    url: 'api/'+ api + "/" + data._id,
    data: data  
  })
  .then(updateItemSuccess, data)
  .catch(updateItemError);
}


function addItem(newItem, api){
  return $http({
    method: 'POST',
    url: 'api/' + api,
    data: newItem  
  })
  .then(updateItemSuccess, newItem)
  .catch(updateItemError);
}

function deleteItem(data, api){
  var titleDeleted = data.title;
  return $http({
    method: 'DELETE',
    url: 'api/'+ api + "/" + data._id,
    titleDeleted: titleDeleted
  })
  .then(updateItemSuccess, titleDeleted)
  .catch(updateItemError);
}  

要复习的内容很多,但希望这能给您一些启发。这些都只是代码的一小部分。我从所有不同来源获取了 mean stack 的信息,但主要根据 pluralsight 的课程重构了所有内容。