Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Node.js and Express middleware refactor

I recently went about restructuring an application I am building to fit the service oriented architecture. I really liked the way a certain tutorial structured his code, so I was trying to replecate a similiar strucutre in my app.

I want to abstract all my middleware out of app.js in my root so that basically all my app.js folder does is configure my express app. I would like to abstract all my middleware out of app.js, and configure it in my index.js folder located in my server directory. You can check my github repo below.

Please check the example repo, I would like to set up my code like this but am having lots of difficulty. Every time I try and take the middleware out of app and run it by requiring into index my app breaks.

Github Repo

I am trying to structure my code like so.

Example Repo

App.js (located in root)

const express = require('express');
const app = require('./server/index');
const mongoose = require('mongoose');
const passport = require('passport');
const dotenv = require('dotenv');
dotenv.config();

const port = process.env.PORT || 3000;

require('./server/config/passport')(passport);

// DB Config
const db = process.env.MongoURI;

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {console.log('MONGODB Connected')})
  .catch(err => console.log(err))



app.listen(port, () => {
  console.log(`Running on port ${port}`);
});




index.js (located in server directory)

const express = require('express');
const app = express();
const api = require('./api/api');


const indexRouter = require('./api/index/indexRouter');
const usersRouter = require('../server/api/user/userRoutes');

require('./middleware/appMiddleware')(app);


app.use('/', indexRouter);
app.use('/users', usersRouter);


module.exports = app;

appMiddleware.js (located in middleware directory which is inside server directory)

const createError = require('http-errors');
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const dotenv = require('dotenv');
dotenv.config();

module.exports = function(app) {
app.use(expressLayouts);
app.set('views', path.join(__dirname, '../../views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

app.use((req, res, next) => {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
})
};

Terminal Error

Error: Failed to lookup view "error" in views directory "/Users/jojovera/Documents/fantasyfootball/views"
    at Function.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/application.js:580:17)
    at ServerResponse.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/response.js:1008:7)
    at ServerResponse.res.render (/Users/jojovera/Documents/fantasyfootball/node_modules/express-ejs-layouts/lib/express-layouts.js:77:18)
    at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:55:7
    at Layer.handle_error (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:315:13)
    at /Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:275:10)
    at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:44:3
    at Layer.handle [as handle_request] (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:317:13)
    at /Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/jojovera/Documents/fantasyfootball/node_modules/express/lib/router/index.js:275:10)
    at /Users/jojovera/Documents/fantasyfootball/server/middleware/appMiddleware.js:39:3

question from:https://stackoverflow.com/questions/66057737/node-js-and-express-middleware-refactor

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...