Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save denefi/860efda2e1ac6f593ded3901102915db to your computer and use it in GitHub Desktop.
Save denefi/860efda2e1ac6f593ded3901102915db to your computer and use it in GitHub Desktop.
Express Cheatsheet: GET (route params & query string) + POST (request body)

Intro

Here's some ways of passing information from a client to a server:

  • In the URL:

    • Route Params (ex. https://localhost:3000/artists/madonna)
    • Query String (ex. https://localhost:3000/search?maxPrice=200)
  • In the BODY of the http request:

    • With some http request methods (for example, POST and PUT), it is possible to send additional data in what is called the "request body".

URL: Route Params

  • Example URL:

  • How to use route params in Express:

    • In your route's path: define the name for the params you expect

      app.get('/artists/:artistname/', (req, res) => {
          
      });
    • Now we can get the info from req.params...

      app.get('/artists/:artistname/', (req, res) => {
          console.log(req.params); //req.params is an object
          const artist = req.params.artistName;
      });
  • Note: it is also possible to define multiple params. For example:

    app.get('/artists/:artistname/albums/:albumName', (req, res) => {
        const artist = req.params.artistName;
        const album = req.params.albumName;
    });

URL: Query String

  • Example URL:

  • How to use query string in Express

    • Read from the object req.query

    • For example, if we receive a request GET https://localhost:3000/search?maxPrice=120

      app.get('/search', (req, res) => {
          console.log(req.query); // req.query is an object
          const price = req.query.maxPrice;
      });
  • Note: we can also pass multiple options in the query string:

    • For example, if we receive a request GET https://localhost:3000/search?maxPrice=120&location=berlin

      app.get('/search', (req, res) => {
          const price = req.query.maxPrice;
          const location = req.query.location;
      });

Request Body

  • Data is sent in the 'body' of the http request (also called 'payload').

  • How to read data from the body in Express

    1. We need to configure the package body-parser (no need to install since it comes with Express):
        const bodyParser = require('body-parser');
        
        // ...
        
        app.use(bodyParser.urlencoded({ extended: true }));
    1. Then we can read data from the object req.body
    app.post('/login', (req, res) => {
        console.log(req.body)
        if(req.body.email === 'bob@bob.com'){
            //...
        }
    })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment