Notes

Routing

Edit on GitHub

Node
3 minutes
  • Routing is all about handling routes, .i.e URL paths. What to do/present/show when someone goes to a route (aka a URL or a path)
  • routes are URL handling code
1// Route definition structure
2app.METHOD(PATH, HANDLER)
  • The METHOD could be any http method (GET, POST, PUT, DELETE etc.). You can also use all as a catchall for any method supported in the http module (it’ll execute the handler for the URL regardless of the method you are using) app.all(PATH, HANDLER)
  • The HANDLER could be a callback function, or a file (module) that has the router defined (containing all the routes)
 1// Routing in Express.js
 2// path: ./routes/index.js
 3const express = require('express');
 4const router = express.Router();
 5
 6router.get('/', (request, response) => {
 7  response.send('Hey it works!');
 8})
 9
10module.exports = router;
1// path: ./app.js
2const routes = require('./routes/index'); // import our routes
3
4app.use('/', routes); // use the routes file whenever anyone goes to /anything
5app.use('/admin', adminRoutes); // You can have multiple route handlers

Callback / Handlers

1app.all('/secret', (request, response, next) => {
2  response.send('ha!');
3  next() // pass control to the next handler
4});

In the response (it doesn’t have to be called response, it’s just a variable name you’ll use inside the function, you can call it dodo for all that matters, but you’ll most commonly see it defined as res), you can:

  • console.log() things
  • send back text .send()
  • send back JSON data .json()
  • if you send data twice (e.g. using both .send() and .json()), you’re gonna get headers are already sent. So make sure you’re never sending data more than once.
  • next is for when you don’t want to send any data back or want to pass it along to something else
1router.get('/', (req, res) => {
2  let profile = { name: 'Aamnah', age: 100, cool: true };
3  console.log('chal gya!');
4  res.send('chal gya code');
5  res.json(profile);
6})
  • request.query() access Query strings
  • request.params() access URL Parameters
  • request.body() access POSTed values

Query strings

From the request you can extract any data that was passed via the URL

For example:

http://localhost:7777/?name=Aamnah&age=100
1router.get('/', (req, res) => {
2  res.send(req.query); // {"name":"\"Aamnah\"","age":"100"}
3  res.send(req.query.name); // Aamnah
4  res.send(req.query.age);  // 100
5})

req.query is an object full of all the query parameters

Parameters

  • : specifies parameters
1router.get('/profile/:name', (req, res) => { // :name is a variable
2})

Now it’ll handle URLs in the structure of /profile/whomever, where whomever is the value of the name parameter. You can access these parameters values like so:

1router.get('/profile/:name/:role', (req, res) => { // http://127.0.0.1:7777/profile/aamnah/admin
2  res.send(`${req.params.name}'s role is ${req.params.role}`); // aamnah's role is admin
3})

Here’s some code to reverse any string sent to a URL endpoint

1router.get('/reverse/:string', (request, response) => { // localhost:port/reverse/aamnah is awesome
2  let reverse = [...request.params.string].reverse().join(''); // using ES6 spread syntax here
3  response.send(reverse); // emosewa si hanmaa
4})