Basic routing

suggest change

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. It expects a path as the first argument and a handler for that path, which receives the request and response objects. For the basic HTTP methods, the routes are:

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

// POST www.domain.com/myPath
app.post('/myPath', function (req, res, next) {})

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

// DELETE www.domain.com/myPath
app.delete('/myPath', function (req, res, next) {})

You can check the complete list of supported verbs here. If you want the same behavior for one path and every HTTP method, use app.all. app.use does not filter by method, and a path prefix also matches requests under that path.

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

or

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

or

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

// no path matches every path

You can chain route definitions for a single path:

app.route('/myPath')
  .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 www.domain.com/myPath
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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents