Node Express.js Routing and Methods

Natan Cabral
2 min readSep 2, 2021

Method Description

res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

var express = require('express');
var app = express();

// respond with "hello world" when a GET request
app.get('/', function (req, res, next) {
res.send('hello world');
});
app.listen(3555,function(){
// http://localhost:3555
console.log("running server");
});

app.route()

You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.

Here is an example of chained route handlers that are defined by using app.route().

app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})

express.Router

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.

The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.

Create a router file named birds.js in the app directory, with the following content:

var express = require('express');
var router = express.Router();
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next();
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router

Then, load the router module in the app:

var app = express();var birds = require('./birds')
app.use('/birds', birds);
app.listen(3555,function(){
console.log("running server");
});

The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

;) Easy

--

--

Natan Cabral

Full Stack Developer | Dev Java, Node.js, TypeScript, React.js, Vue.js, Express.js, Next.js, Rest API, Laravel, Databases, MongoDB, Unix distro and Open Source