Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Last active March 10, 2022 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregfenton/d0dc5b82feb08bcf5bcf0ea48a92149a to your computer and use it in GitHub Desktop.
Save gregfenton/d0dc5b82feb08bcf5bcf0ea48a92149a to your computer and use it in GitHub Desktop.
Express: Handling URL query parameters

Express: Handling URL query parameters

Prerequisites

  1. Express "Hello World!" app created.

Assumptions

  1. GET request includes query parameters after the ? symbol. Example:

    http://locahost:4000/forest?daylight=true
    
    • URL query parameters are automatically parsed by Express and are defined in the request.query object.

Instructions

  1. Create a route handler for an endpoint of your choice:

    app.get('/forest', (request, response) => {
      response.send("You are in a deep, dark wood...");
    })
  2. Add a conditional message based on a URL query parameter:

    app.get('/forest', (request, response) => {
      let daylight = request.query.daylight;
    
      if (daylight === 'true') {
        response.send("You are in a deep, decently lit wood...");
      } else {
        response.send("You are in a deep, dark wood...");
      }
    })
{
"name": "express-post-requests",
"version": "1.0.0",
"description": "An introduction to handling POST requests",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "InceptionU",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
}
}
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
app.listen(PORT, function() {
console.log(`Example app listening at port: ${PORT}`);
})
app.get('/', (request, response) => {
response.send("Hello World!");
})
app.get('/forest', (request, response) => {
let daylight = request.params.daylight;
if (daylight === 'true') {
response.send("You are in a deep, recently lit wood...");
} else {
response.send("You are in a deep, dark wood...");
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment