尝试重构Express路线

时间:2019-03-08 15:07:37

标签: node.js express routes

所以我在使用Hackathon Starter并尝试重构路由,但遇到了一些麻烦或麻烦:

我像这样在app.js中重构了控制器

/**
 * Controllers (router handlers)
 * Refactored
 */
const homeController = require('./controllers/home/index');
const userController = require('./controllers/users/index');
const apiController = require('./controllers/api/index');
const contactController = require('./controllers/contact/index');

With the index.js file just being the routes
const express = require('express');
const homeController = require('./homeController');

const app = express();
app.get('/', homeController.index);

module.exports = app;

在app.js中-我所有的路由都在这里:

app.use('/', homeController);
app.use('/user', userController);
app.use('/contact', contactController);
app.use('/api', apiController);

本国路线正常运行-就是这样。当我访问/ login或/ contact时-没有任何效果。我收到错误无法获取/ contact

UDPATE homeController

/**
 * GET /
 * Home page.
 */
exports.index = (req, res) => {
    res.render('home', {
      title: 'Home'
    });
  };

userController

const bluebird = require('bluebird');
const crypto = bluebird.promisifyAll(require('crypto'));
const nodemailer = require('nodemailer');
const passport = require('passport');
const User = require('../../models/User');
// const User = require('../models/User'); default

/**
 * GET /login
 * Login page.
 */
exports.getLogin = (req, res) => {
  if (req.user) {
    return res.redirect('/');
  }
  res.render('account/login', {
    title: 'Login'
  });
};

/**
 * POST /login
 * Sign in using email and password.
 */
exports.postLogin = (req, res, next) => {
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('password', 'Password cannot be blank').notEmpty();
  req.sanitize('email').normalizeEmail({ gmail_remove_dots: false });

  const errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/login');
  }

  passport.authenticate('local', (err, user, info) => {
    if (err) { return next(err); }
    if (!user) {
      req.flash('errors', info);
      return res.redirect('/login');
    }
    req.logIn(user, (err) => {
      if (err) { return next(err); }
      req.flash('success', { msg: 'Success! You are logged in.' });
      res.redirect(req.session.returnTo || '/');
    });
  })(req, res, next);
};

/**
 * GET /logout
 * Log out.
 */
exports.logout = (req, res) => {
  req.logout();
  res.redirect('/');
};

/**
 * GET /signup
 * Signup page.
 */
exports.getSignup = (req, res) => {
  if (req.user) {
    return res.redirect('/');
  }
  res.render('account/signup', {
    title: 'Create Account'
  });
};
.... lots more code

0 个答案:

没有答案