简体   繁体   中英

How do I handle Express.js routes?

I've generated Express app. I have an index page, I want to add subscribe form for collecting email form the save index page.

So I added a function to ./routes/index.js:

exports.index = function(req, res){
    res.render('index', { title: 'Express' });
};

exports.subscribe = function(req, res){
    res.send('Subscribed');
};

Here's app.js:

var routes = require('./routes');
//Some code here
app.post('/subscribe', routes.subscribe);

Is that a good way to organise code? I mean, where should I place route handler in such case?

you can do some thing like

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

and then create route.js, which may look like

var index = require('./routes/index');
var users = require('./routes/users');
module.exports = function(app){
app.get('/',index.index);
app.get('/homePage',users.homePage);
};

now as you can see i have created a routes folder to manage all my routes such as index and users. So you can just have a look at the index.js

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

I mean that's the simplest and you can have get or post as per your requirement. This is the standard which you might see everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM