一尘不染

如何在Node.js和Express 4上分开路由?

node.js

我想将路由与server.js文件分开。

我正在Scotch.io上关注本教程 http://scotch.io/tutorials/javascript/build-a-restful-api-
using-node-and-express-4

如果所有行都在server.js文件上,则它可以工作。但是我没有分开。我该如何工作?

server.js

// set up ======================================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// configuration ===============================================================
app.use(bodyParser());

var port = process.env.PORT || 8000;

var mongoose = require('mongoose');
var database = require('./config/database');
mongoose.connect(database.url);
var Video = require('./app/models/video');

// routes =======================================================================
app.use('/api', require('./app/routes/routes').router);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("ready captain, on deck" + port);

module.exports = app;

还有app / routes / routes.js

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

router.use(function(req, res, next) {
  console.log('Something is happening.');
  next();
});

router.get('/', function(req, res) {
  res.json({ message: 'hooray! welcome to our rest video api!' });  
});


router.route('/videos')

  .post(function(req, res) {

    var video = new Video();
    video.title = req.body.title;

    video.save(function(err) {
  if (err)
    res.send(err);

  res.json({ message: 'Video criado!' });
});


  })

  .get(function(req, res) {
    Video.find(function(err, videos) {
      if (err)
        res.send(err);

      res.json(videos);
    });
  });

module.exports.router = router;

阅读 235

收藏
2020-07-07

共1个答案

一尘不染

就将路由与主文件分开而言。

Server.js

//include the routes file
var routes = require('./routes/route');
var users = require('./routes/users');
var someapi = require('./routes/1/someapi');

////////
app.use('/', routes);
app.use('/users', users);
app.use('/1/someapi', someapi);

路线/route.js

//last line - try this
module.exports = router;

同样对于新项目,您可以在命令行上尝试

express project_name

您将需要为此的快递发电机

2020-07-07