在Express中分隔路线

时间:2018-01-09 16:07:07

标签: javascript node.js express backend

编辑#2

知道了,更新了代码

app.js

const express = require('express');
const bodyParser = require('body-parser');
const hbs = require('hbs');
const fs = require('fs');

var app = express();

// Server port
const port = process.env.PORT || 3000;
// Server starting message
app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});

// Views directory established and handbars engine
hbs.registerPartials(__dirname + '/views/layouts')
app.set('view engine', 'hbs');

// static assets rendered
app.use(express.static(__dirname + '/public'));

// body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// server.log setup middleware
app.use((req, res, next) => {
  var now = new Date().toString();
  var log = `${now}: ${req.method} ${req.url}`

  console.log(log);

  fs.appendFile('server.log', log + '\n', (err) => {
    if (err) {
      console.log('Unable to append to server.log');
    }
  });
  next();
});

// Routes
const routes = require('./routes/routes');
app.use("/", routes);

// Get year for footer
hbs.registerHelper('getCurrentYear', () => {
  return new Date().getFullYear()
});

谢谢大家的帮助!

编辑#1

我已将app.use("/", routes)"添加到app.js,但现在当我测试我的联系表单和邮件时,我得到以下内容:

TypeError: Cannot read property 'name' of undefined
    at router.post (/Users/benbagley/Code/poetry-out-loud/routes/routes.js:29:27)
    at Layer.handle [as handle_request] (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/layer.js:95:5)
    at /Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/benbagley/Code/poetry-out-loud/node_modules/express/lib/router/index.js:47:12)

-

原始问题

我目前正在开发一个node.js应用,我试图将我的应用和路由分成不同的文件。

这是我到目前为止所拥有的

app.js

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const hbs = require('hbs');
const fs = require('fs');

const port = process.env.PORT || 3000;
var app = express();

hbs.registerPartials(__dirname + '/views/layouts')
app.set('view engine', 'hbs');

// body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

const routes = require('./routes/routes');

app.use((req, res, next) => {
  var now = new Date().toString();
  var log = `${now}: ${req.method} ${req.url}`

  console.log(log);

  fs.appendFile('server.log', log + '\n', (err) => {
    if (err) {
      console.log('Unable to append to server.log');
    }
  });
  next();
});

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

hbs.registerHelper('getCurrentYear', () => {
  return new Date().getFullYear()
});

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

routes.js

const express = require('express');
const router = express.Router();

// Routes
router.get('/', (req, res) => {
  res.render('index.hbs', {
    pageTitle: 'homepage'
  });
});

router.get('/registration', (req, res) => {
  res.render('registration.hbs', {
    pageTitle: 'Registration'
  });
});

router.get('/login', (req, res) => {
  res.render('login.hbs', {
    pageTitle: 'Login'
  });
});

router.post('/send', (req, res) => {
  const output = `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <br>
    <ul>
    <li>Name: ${ req.body.name }</li>
    <li>Name: ${ req.body.email }</li>
    </ul>

    <h3>Message:</h3>
    <p>${ req.body.message }</p>
  `;

  nodemailer.createTestAccount((err, account) => {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: "smtp.mailtrap.io",
      port: 2525,
      auth: {
        user: "xxxxxxx",
        pass: "xxxxxxx"
      }
    });
    // setup email data with unicode symbols
    let mailOptions = {
      from: `"${req.body.name}" <${req.body.email}>`, // sender address
      to: 'xxxxxxxxx', // list of receivers
      subject: 'New contact message', // Subject line
      html: output // html body
    };
    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        return console.log(error);
      }

      console.log('Message sent: %s', info.messageId);
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      res.render('index', {
        pageTitle: 'Thank you'
      });
    });
  });
});

module.exports = router;

接收的当前终端输出

Server is up on port 3000
Tue Jan 09 2018 15:58:40 GMT+0000 (GMT): GET /
[nodemon] restarting due to changes...
[nodemon] starting `node app.js hbs, css`
Server is up on port 3000

在浏览器中我正在

browser screenshot

这是文件结构的截图

enter image description here

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

我还是新手,但我在基本网址上使用了以下内容:
app.get('/', (req, res) => { res.json('ready for your queries'); });
哪里 app = express()
这是一个简单的代码,让我知道服务器正在运行而不与其他服务做任何事情。

答案 1 :(得分:0)

您应该选择经过测试的解决方案。我喜欢使用快速发电机。它为您创造了一个很好的结构:

-bin
 www
-config
-public
 -javascripts
 -stylesheets
 -images
-routes
 index.js
 something.js
-views
 index.ejs
 something.ejs
app.js

bin / www保存您的服务器设置,app.js是您加载配置,路线和模型的地方(如果您使用的是数据库)。 http://expressjs.com/en/starter/generator.html

将代码移动到此结构中不会有太多麻烦。如果你有疑问,请随便询问。

答案 2 :(得分:0)

Your code will be      

app.js 

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const hbs = require('hbs');
const fs = require('fs');

var app = express();

const port = process.env.PORT || 3000;
const routes = require('./routes/routes');


hbs.registerPartials(__dirname + '/views/layouts')
app.set('view engine', 'hbs');

// body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

router(app);

app.use((req, res, next) => {
    var now = new Date().toString();
var log = `${now}: ${req.method} ${req.url}`

console.log(log);

fs.appendFile('server.log', log + '\n', (err) => {
    if (err) {
        console.log('Unable to append to server.log');
    }
});
next();
});

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

hbs.registerHelper('getCurrentYear', () => {
    return new Date().getFullYear()
});

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


routes.js


module.exports = function (app) {

   app.get('/', (req, res) => {   res.render('index.hbs', {   pageTitle: 'homepage'  }); });

    router.get('/login', (req, res) => {  res.render('login.hbs', { pageTitle: 'Login'  }); });

..... Remaining function
}