[英]How do I handle Express.js routes?
I've generated Express app. 我已经生成了Express应用。 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: 所以我在./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: 这是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 然后创建route.js,看起来像
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 所以你可以看看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. 这是您随处可见的标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.