Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

node.js - separate file for routes in express

I was wondering how do I move all of my api routes in express into a separate routes.js file from my server.js file

I have a long list of api routes using app.use() for each route. So each route is in its own file, e.g. movies.js, movie.js but when I list these it makes for a long list in server.js

So I want to remove the list of api endpoints section from the below server.js out to a routes.js file.

Here is what I have currently:

server.js

import path from 'path'
import express from 'express'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackConfig from './webpack.config.dev'

const app = express();

/* api endpoints, can be many more, I want them in routes.js */    
app.use('/api/movies', require('./src/api/routes/movies'))
app.use('/api/movie', require('./src/api/routes/movie'))

app.use(webpackDevMiddleware(webpack(webpackConfig), {
  publicPath: webpackConfig.output.publicPath
}));

app.use('/public', express.static(__dirname + '/public'))    

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});


app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }
})

An example route

movies.js

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

router.get('/', function(req, res) {
  res.json({})
});

module.exports = router;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try to use the following modular approach. Define controller files having logic per feature. e.g. movie.

movieController.js

module.exports = {
    getMovie : function(req, res){
       //do something
    },
    getMovies : function(req, res){
       //do something
    },
    postMovie : function(req, res){
       //do something
    }
}

Then, reference that controller in routes files and simply plug those functions.

routes.js

var express = require('express');
var movieCtrl = require('./movieController');

var router = express.Router();

router.route('/movie').get(movieCtrl.getMovie);
router.route('/movie').post(movieCtrl.postMovie);
router.route('/movies').get(movieCtrl.getMovies);

module.exports = router;

And, in app.js, mount the routes to suitable location, e.g. /api

app.js

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...