[英]How do I handle Express.js routes?
我已經生成了Express應用。 我有一個索引頁面,我想添加訂閱表單以收集保存索引頁面的電子郵件。
所以我在./routes/index.js中添加了一個函數:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.subscribe = function(req, res){
res.send('Subscribed');
};
這是app.js:
var routes = require('./routes');
//Some code here
app.post('/subscribe', routes.subscribe);
這是組織代碼的好方法嗎? 我的意思是,在這種情況下應將路由處理程序放在哪里?
你可以做一些像
app.use(app.router);
var routes = require('./routes')(app);
然后創建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);
};
現在,如您所見,我已經創建了一個路由文件夾來管理我的所有路由,例如索引和用戶。 所以你可以看看index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
我的意思是這是最簡單的,您可以根據需要進行獲取或發布。 這是您隨處可見的標准。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.