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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…