Well - the more I read the more confused I get. So here the source:
var express = require('express')
, http = require('http')
, server = express()
;
var home = require('./routes/home.js')
, about = require('./routes/about.js')
, contact = require('./routes/contact.js');
server.configure(function () {
server.set('port', process.env.PORT || 3000);
server.set('view engine', 'hjs');
server.set('views', __dirname + '/views');
server.use(express.logger());
server.use(server.router);
server.use(express.favicon());
server.use(require('stylus').middleware(__dirname + '/public'));
server.use(express.static(__dirname + '/public'));
server.use(express.bodyParser());
server.use(express.cookieParser('your secret here'));
server.use(express.methodOverride());
server.use(express.session());
});
server.get('*', function (req, res) {
switch (req.path) {
case '/':
res.render('home', { title:'Home Page' });
break;
case '/about/':
res.render('home', { title:'About Page' });
break;
case '/contact/':
res.render('contact', { title:'Contact Page' });
break;
default:
res.render('home', { title:'404 - Page not found'});
}
});
Well it's working, but I still don't get that req/res combo into my skull. I'm pretty sure I don't need '*'
there as a parameter. However I don't know how to build up a better solution. Any simple dumb stupid exmaples so I could visualize how exactly the magic works.
To simplify my riddle I'd like to know (and understand) why this works:
server.get('*', function (req, res) {
but this doesn't
server.get(function (req, res) {
the first parameter is always being handled as what exectly?
I believe the first parameter is the route. You can break up your code into the following which might make more sense, and would follow convention:
server.get('/', function (req, res) {
res.render('home', { title:'Home Page' });
})
server.get('/contact/', function (req, res) {
res.render('contact', { title:'Contact Page' });
});
server.get('*', function (req, res) {
res.render('Page Not Found', 404);
});
And so forth...
The '*'
that you are using just accepts all routes. Similar to a wildcard!
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.