Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active November 4, 2021 15:15
Show Gist options
  • Save acidtone/f470990b7ebd01907a37118f200b17ab to your computer and use it in GitHub Desktop.
Save acidtone/f470990b7ebd01907a37118f200b17ab to your computer and use it in GitHub Desktop.
Express Activity: Create a JSON endpoint using route parameters

Express Activity: Create a JSON endpoint using route parameters

In this activity, you'll be refactoring a sample Express server using the spoilers from this activity: Find an object in an array.

Instructions

  1. Download or fork/clone this Gist into your workspace.
  2. Using this sample code for Array.find(), define an array of objects called guild.
  3. Refactor the GET /api/guild/:class endpoint so that it returns a single guild member that matches the requested :class route parameter.
  4. Return a JSON 404 Not Found response if the :class isn't found.
{
"name": "express-params-starter",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"keywords": [],
"author": "Tony Grimes",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
}
}
// Install modules
const express = require('express')
const app = express()
// Define seed data
// Your data here
const guild = [];
// Dynamic JSON Endpoint
app.get('/api/guild', function(request, response) {
response.send(guild)
})
app.get('/api/guild/:name', function(request, response) {
const character = 'Array.find()'; // Use Array.find() here
response.send(character)
})
// Handle 404 errors with middleware
app.use(function(request, response) {
response.status(404)
response.send('404: File Not Found')
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, function(){
console.log(`Listening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment