I'm reading an intro book about ExpressJS and unfortunately they are using Express 3.x. I am trying to get their code example updated to Express 4.x. Here is their example:
routes/index.js
exports.index = function(req, res){
res.send('welcome');
};
app.js
var express = require('express');
var http = require('http');
var app = express();
// Load the route handlers
var routes = require('./routes');
// Add router middleware explicitly
app.use(app.router);
// Routes
app.get('/', routes.index);
http.createServer(app).listen(3000, function(){
console.log('App started');
});
Here, app.router
is deprecated and node throws an error about it. I have updated the code:
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
var routes = require('./routes');
router.get('/', routes.index);
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
http.createServer(app).listen(3000, function() {
console.log('Express app started');
});
However, when visit localhost:3000
, I get this error displayed in the browser:
Cannot GET /
If I remove usage of the Router class entirely (and remove app.use(app.router)
), I can just do:
app.get('/', routes.index);
and that will work.
How do I load my external route with the Router class?
In express 4, you construct your routes using routers.
So, say you have routes/index.js and routes/foo.js, they would look something like this:
// routes/index.js
var router = require('express').Router();
router.get('/', function(req, res){
res.send('Hello!');
});
module.exports = router;
// routes/foo.js
var router = require('express').Router();
router.get('/bar', function(req, res){
res.send('foobar');
});
module.exports = router;
In your main server file you can then app.use these routers, attaching them at various places. You could also do router.use to attach routers to routers (eg /users/user-id/pictures/picture-id kind of routes).
// server.js
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use('/', require('./routes/index'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/foo', require('./routes/foo'));
app.listen(3000);
And you should now be able to GET / and GET /foo/bar.
For a bit more technical correctness, you should also be including middleware only on routes that need it.
You can do this per router, or per endpoint.
router.use(bodyParser.json());
// or
router.route('/baz')
.use(bodyParser.json())
.post(function(req, res){
res.status(201).json(req.body);
});
This is generally good to do, but also can be very important in some cases, eg handling file uploads.
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.