I have the following script in my index.js page -
app.get('/', function(request, response) {
response.render('index', {
foo: "bar"
})
})
This is working fine, but I want to have the response.render
code in a different file, as there is going to be a lot of code behind it.
Or basically, I want to get another file to call the app.get()
method for the root ("/")
path, and some other file to call the method for the '/admin'
path, and another for '/post'
path. Any way to do it ?
CodePudding user response:
What you could do is create a new javascript file with export modules to handle the routes. I'm not sure if you will be able to move the app.get()
methods to a different JS file, but here's something you can do:
server.js:
const manageIndexRoute = require("./manageindex.js");
app.get('/', manageIndexRoute)
manageindex.js
module.exports = (req, res) => {
res.render('index', {
foo: "bar",
...
})
...
}
CodePudding user response:
This can be achieved suing a router
You can make a new file called indexRoute
and require it into your index.js
indexRoute = require("./indexRoute")
Then underneath that, add
app.use('/', indexRoute)
Now go into the indexRoute.js
file and add the following code:
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Birds home page')
})
module.exports = router
There. this directs all trafic from http://example.com/
to this file
But there is an alternative i guess
You can make a new file called indexHandler
and require it into your index.js
indexHandler = require("./indexHandler")
Then change your app.get call to this:
app.get('/', function(request, response) => indexHandler)
Now go into the indexRoute.js
file and add the following code:
indexHandler = (request, response) => {
response.render('index', {
foo: "bar"
})
}
module.exports = indexHandler