我想将路由与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;
答案 0 :(得分:53)
<强> 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/
答案 1 :(得分:51)
就涉及从主文件分离路线而言..
<强> 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
你需要快速发电机
答案 2 :(得分:23)
使用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;
})();
答案 3 :(得分:11)
将路由分隔到自己的文件中的一种方法。
<强> 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
}
答案 4 :(得分:2)
我遇到的一个问题是在使用router时尝试使用方法记录路径。最终使用此方法来解决它。允许您将路径保持在较高级别的较低路由器级别。
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;
如果您记录路由器堆栈,您实际上可以看到路径和方法
答案 5 :(得分:1)
$ npm install express-routemagic --save
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
就是这样!
project_folder
|--- routes
| |--- api
| |--- videos
| | |--- index.js
| |
| |--- index.js
|
|--- server.js
请注意,在路由下有一个结构。 Route Magic具有文件夹识别功能,将自动暗示它是您的api uri结构。
只需两行代码:
const magic = require('express-routemagic')
magic.use(app, __dirname, 'routes')
const router = require('express').Router()
router.get('/', (req, res) => {
res.json({ message: 'hooray! welcome to our rest video api!' })
})
Route Magic知道您的文件夹结构,并为您的api设置了相同的结构,因此该网址为
api/videos
const router = require('express').Router()
router.post('/', (req, res) => { /* post the video */ })
router.get('/', (req, res) => { /* get the video */ })
免责声明:我写了包裹。但这确实是早该完成的工作,已经等到有人写了。
答案 6 :(得分:0)
在我的情况下,我喜欢尽可能多的打字稿。以下是我如何使用类组织我的路线:
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) => {
});
}
答案 7 :(得分:0)
如果您将 express-4.x 与 TypeScript 和ES6一起使用,这将是一个最佳模板;
src/api/login.ts
import express, { Router, Request, Response } from "express";
const router: Router = express.Router();
// POST /user/signin
router.post('/signin', async (req: Request, res: Response) => {
try {
res.send('OK');
} catch (e) {
res.status(500).send(e.toString());
}
});
export default router;
src/app.ts
import express, { Request, Response } from "express";
import compression from "compression"; // compresses requests
import expressValidator from "express-validator";
import bodyParser from "body-parser";
import login from './api/login';
const app = express();
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.get('/public/hc', (req: Request, res: Response) => {
res.send('OK');
});
app.use('/user', login);
app.listen(8080, () => {
console.log("Press CTRL-C to stop\n");
});
非常清晰可靠,而不是使用var
和module.exports
。