I have the following structure
project
-app/
--controllers/
---home.js
--models/
---home.js
--views/
---home.html
-db/
--db.js
-index.js
my controller home.js looks like this:
var express = require('express');
var router = express.Router();
var database = require('../models/home');
var path = require('path');
router.get("/", function(request, response) {
response.sendFile(path.join(__dirname, '../views', 'home.html'));
});
module.exports = router;
Now I want to make that route useful, so in my index.js
I have:
var express = require('express');
var app = express();
var port = 3000;
app.use(require('./app/controllers/home')); //<-- this is what I ask for
app.listen(3000, function(err ) {
//......
})
But now I have more then just route to 'home', so instead of
app.use(require('./app/controllers/home'));
app.use(require('./app/controllers/about'));
app.use(require('./app/controllers/etc'));
I read that I can use:
app.use(require('./app/controllers/'));
But I get error that the module cannot be found. Can you suggest me how can I easily get all my routes in use? Thanks :)
If I understand your question right you're trying to route a router to a different relative path. You can set a relative path by passing that path as the first parameter. Then any route inside of your router that uses app.get/use/... will start from that relative path.
Inside index.js
app.use("/home", require('./app/controllers/home'));
app.use("/about", require('./app/controllers/about'));
app.use("/etc", require('./app/controllers/etc'));
inside ./app/controllers/home and other routes
router.get("/", ...) // this will be located at localhost/home
router.get("/myhouse, ...) // this will be located at localhost/home/myhouse
Also worth metioning you can route a router inside a router
router.use("/", require('path/to/another-router.js'))
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.