Node.js Basic routing


First create an express app:

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

Then you can define routes like this:

app.get('/someUri', function (req, res, next) {})

That structure works for all HTTP methods, and expects a path as the first argument, and a handler for that path, which receives the request and response objects. So, for the basic HTTP methods, these are the routes

// GET
app.get('/myPath', function (req, res, next) {})

// POST'/myPath', function (req, res, next) {})

// PUT
app.put('/myPath', function (req, res, next) {})

app.delete('/myPath', function (req, res, next) {})

You can check the complete list of supported verbs here. If you want to define the same behavior for a route and all HTTP methods, you can use:

app.all('/myPath', function (req, res, next) {}) 


app.use('/myPath', function (req, res, next) {})


app.use('*', function (req, res, next) {})

// * wildcard will route for all paths

You can chain your route definitions for a single path

  .get(function (req, res, next) {})
  .post(function (req, res, next) {})
  .put(function (req, res, next) {})

You can also add functions to any HTTP method. They will run before the final callback and take the parameters (req, res, next) as arguments.

// GET
app.get('/myPath', myFunction, function (req, res, next) {})

Your final callbacks can be stored in an external file to avoid putting too much code in one file:

// other.js
exports.doSomething = function(req, res, next) {/* do some stuff */};

And then in the file containing your routes:

const other = require('./other.js');
app.get('/someUri', myFunction, other.doSomething);

This will make your code much cleaner.