Reputation: 37
I was reading the MEAN MACHINE Book and was following its instructions under Routing Node applications [ pg - 36]
The express.Router()⁴⁸ acts as a mini application. You can call an instance of it (like we do for Express) and then define routes on that. Let’s look at an example so we know exactly what this means. Add this to your ‘server.js’ file if you’d like to follow along. Underneath our app.get() route inside of server.js, add the following. We’ll 1. call an instance of the router 2. apply routes to it 3. and then add those routes to our main app
Accordingly I copy-pasted the code [ pls see below] http://localhost:1337/admin Page throws an error saying " Cannnot GET/admin "
Code :
// load the express package and create our app
var express = require('express');
var app = express();
var path = require('path');
// send our index.html file to the user for the home page
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
// create routes for the admin section
// get an instance of the router
var adminRouter = express.Router();
// route middleware that will happen on every request
// admin main page. the dashboard (http://localhost:1337/admin)
adminRouter.get('/', function(req, res) {
res.send('I am the dashboard!');
});
// users page (http://localhost:1337/admin/users)
adminRouter.get('/users', function(req, res) {
res.send('I show all the users!');
});
// posts page (http://localhost:1337/admin/posts)
adminRouter.get('/posts', function(req, res) {
res.send('I show all the posts!');
// apply the routes to our application
app.use('/admin', adminRouter);
});
// start the server
app.listen(1337);
console.log('1337 is the magic port!');
Upvotes: 0
Views: 65
Reputation: 853
adminRouter.get('/posts', function(req, res) {
res.send('I show all the posts!');
// apply the routes to our application
app.use('/admin', adminRouter);
});
Use app.use outside the middleware.
adminRouter.get('/posts', function(req, res) {
res.send('I show all the posts!');
})
// apply the routes to our application
app.use('/admin', adminRouter);
Upvotes: 0
Reputation: 944086
The line app.use('/admin', adminRouter);
adds the adminRouter to the main application.
You have that inside the function that gets called for /posts
on that router.
Consequently, it never gets called.
You need to move it down so it appears between });
and // start the server
Upvotes: 1