http://expressjs.com/en/guide/routing.html
app.get
app.post
app.delete
.head
, .put
, .patch
, .options
, ...express-app/start/counter.js
GET /greet
replies 'Hello, you!'POST /count
Increments a counterGET /count
replies with the current countDELETE /count
sets count to 0Hints:
Extra Credit:
*
can match any number of characters.
app.get('/users/*`, handleUsers);
Routes can be Regular Expressions
app.get(/.*nodejs$/, function(req, res) {
res.send('Your request path ended with "nodejs"!');
});
app.get('*', function(req, res) {
res.send('you requested something else');
});
app.get('/test', function(req, res) {
res.send('you requested /test');
});
Order matters!
express-app/start/wildcard-route.js
GET /test/
alone replies "you requested '/test/'"GET /test/[any number of characters]
replies "you requested '/test/something'"Extra Credit:
Up Next: the request
object
request
Objecthttp://expressjs.com/en/4x/api.html#req
req.app
req.body
req.path
req.query
req.params
req.xhr
req.method
HTTP.IncomingMessage
url.parse
not neededquerystring.parse
not needed// misc/req.params.js
var server = require('express')();
// example: GET /?foo=bar
server.get('/', function(req, res){
res.send('foo is... ' + req.query.foo);
});
server.listen(3000);
var server = require('express')();
server.get('/:foo', function(req, res){
res.send(':foo is... ' + req.params.foo);
});
server.listen(3000);
start/restaurants-server-1.js
:
/restaurants/2
replies...Hints:
var users = [
{ id: 1, name: 'Qian' },
{ id: 2, name: 'Zeynep'},
{ id: 3, name: 'Raisel'}
];
var qian = findById(users, 1);
Up Next: the response
object
response
Objecthttp://expressjs.com/en/4x/api.html#res
res.send(string|buffer|object)
res.json(object)
res.status(httpStatusCode)
res.set(headerName, headerValue)
res.set({name: 'value'})
res.redirect(url)
res.sendFile(path, options, callback)
res.download(path)
res.render(template, data)
res.send
res.send('<h1>Sequoia\'s WebZone!</h1>');
res.send({ id: 1, name: 'Zeynep' });
res.send(new Buffer('Here is an octet-stream for you!'));
res.json
res.json([
{id : 1, name : 'Sequoia'},
{id : 2, name : 'Jackson'},
{id : 3, name : 'Christine'}
]);
res.json(null)
res.json("<h1>Hello!</h1>");
start/restaurants-server-2.js
/restaurants/:id
route to send json/restaurants/
replies with all restaurants as jsonres.status
res.status(204); // No Content
res.status(404)
.send('Not Found');
///or perhaps
res.status(404)
.json({error : 'Not Found'});
res.status(500)
.sendFile('/var/www/shared/internal_error.html');
res.set
res.set('Content-Type', 'text/markdown');
res.set({
'X-Powered-By' : 'Sequoia\'s #1 Web Framwork!/v2.5',
'X-Favorite-Animal': 'Hamster',
Pragma : 'no-cache'
});
res.redirect
res.redirect('http://other.url.com');
// GET /admin/users/
res.redirect('../login');
// => /admin/login
res.sendFile
Takes (optional) callback with error-first function signature
function fileSent(err){
if(err){
console.error(err);
res.status(err.status).end();
}
}
var options = { root: '/var/static/' };
res.sendFile('app.js', options , fileSent);
res.sendFile
app.get('/assets/protected/:filename' function(req,res){
if(req.user && hasAccess(req.params.filename, req.user)){
res.sendFile(req.params.filename, options, fileSent);
}else{
res.status(403).send('Not Authorized');
}
});
// @return Boolean : true if user has access to requested file
function hasAccess(file, user){ /*...*/
res.download
res.download('/path/to/file.ext');
res.download('/path/to/file.ext', 'response.txt');
res.download('/path/to/file.ext', 'response.txt', fileSent);
res.render
http://expressjs.com/en/guide/using-template-engines.html
res.render('index');
res.render('userList', users);
res.render('user', {
name: 'Michelle',
role: 'Admin'
});
// user-router.js
var router = require('express').Router();
module.exports = router;
router.get('/', allUsersHandler);
router.get(':id', getUserHandler);
router.post('/', createUserHandler);
// server.js
var app = require('express')();
var userRouter = require('./user-router');
app.use('/users/', userRouter);
// ...
start/restaurants-server-3.js
/restuarants/
routes to new external module/restaurants
(paths work as before)Hints:
/foo
, don't put /foo
in router paths!! //fooRouter.js
var Router = require('express').Router;
var router = module.exports = Router();
router.get('/' /*...*/);
var router = require('./fooRouter')
app.use('/foo', router);
Up Next: Middleware