如何分离Node.js和Express 4上的路线?

我想从我的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; 

和应用程序/路线/ 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; 

就从主文件分离路线而言。

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 

你将需要快递发电机

Server.js

 var express = require('express'); var app = express(); app.use(express.static('public')); //Routes app.use(require('./routes')); //http://127.0.0.1:8000/ http://127.0.0.1:8000/about //app.use("/user",require('./routes')); //http://127.0.0.1:8000/user http://127.0.0.1:8000/user/about var server = app.listen(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) 

routes.js

 var express = require('express'); var router = express.Router(); //Middle ware that is specific to this router router.use(function timeLog(req, res, next) { console.log('Time: ', Date.now()); next(); }); // Define the home page route router.get('/', function(req, res) { res.send('home page'); }); // Define the about route router.get('/about', function(req, res) { res.send('About us'); }); module.exports = router; 

*在routs.js中,您应该定义中间件

ref http://wiki.workassis.com/nodejs-express-separate-routes/

使用Express 4.0将路线分隔成自己的文件的另一种方法是:

server.js

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

routes.js

 module.exports = (function() { 'use strict'; var router = require('express').Router(); router.get('/', function(req, res) { res.json({'foo':'bar'}); }); return router; })(); 

一种将路线分隔成自己的文件的方法。

SERVER.JS

 var routes = require('./app/routes/routes'); //module you want to include var app=express(); routes(app); //routes shall use Express 

ROUTES.JS

 module.exports=function(app) { //place your routes in here.. app.post('/api/..., function(req, res) {.....} //example } 

就我而言,我喜欢尽可能多的打字稿。 下面是我如何组织我的路线与类:

 export default class AuthService { constructor() { } public login(): RequestHandler { return this.loginUserFunc; } private loginUserFunc(req: Request, res: Response): void { User.findOne({ email: req.body.email }, (err: any, user: IUser) => { if (err) throw err; if(!user) return res.status(403).send(AuthService.noSuccessObject()); else return AuthService.comparePassword(user, req, res); }) } } 

从你的server.js或你有你的服务器代码,你可以通过以下方式调用AuthService:

 import * as express from "express"; import AuthService from "./backend/services/AuthService"; export default class ServerApp { private authService: AuthService; this.authService = new AuthService(); this.myExpressServer.post("/api/login", this.authService.login(), (req: express.Request, res: express.Response) => { }); } 

我遇到的一个问题是在使用router.use时使用方法尝试loggingpath,最终使用此方法来解决它。 允许您保持更高级别的路由器级别。

routes.js

 var express = require('express'); var router = express.Router(); var posts = require('./posts'); router.use(posts('/posts')); module.exports = router; 

posts.js

 var express = require('express'); var router = express.Router(); let routeBuilder = path => { router.get(`${path}`, (req, res) => { res.send(`${path} is the path to posts`); }); return router } module.exports = routeBuilder; 

如果你login路由器堆栈,你可以看到path和方法