Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active February 28, 2024 09:27
Show Gist options
  • Save luisjunco/68bb7f09b8e95f225c67aece04522cf1 to your computer and use it in GitHub Desktop.
Save luisjunco/68bb7f09b8e95f225c67aece04522cf1 to your computer and use it in GitHub Desktop.
Express Cheatsheet: GET (route params & query string) + POST (request body)

Intro

This cheatsheet covers the following topics:

  1. URL: Route Params
  2. URL: Query String
  3. Request Body

URL: Route Params

  • Example URL:

  • How to use route params in Express:

    1. In the path, define a dynamic part with the syntax /:something
    2. Inside the route, read from req.params
  • Example 1:

    app.get('/artists/:artistname/', (req, res) => {
        console.log(req.params); //req.params is an object
        const artist = req.params.artistName;
    });
  • Example 2 (multiple route params):

    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 read data from the query string: req.query

  • Example 1:

    • 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;
      });
  • Example 2 (multiple query strings):

    • 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 from the request body:

    • Step 1. Configure Express to be able to read incoming HTTP request that contain JSON data in the body.

      app.use(express.json());
    • Step 2. Read data from the request body: 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