Created
July 27, 2018 23:41
-
-
Save liseferguson/fe3535a2d4f2be3883ee8957c3215ce7 to your computer and use it in GitHub Desktop.
Node 1.1.5 Request and Response Drills
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
***POST DRILL*** | |
// import express | |
const express = require("express"); | |
// init a new express app | |
const app = express(); | |
//tells app to navigate to the endpoint "echo:/what" why are (req, res) in parentheses? | |
//Q: | |
app.get("/echo/:what", (req, res) => { | |
res.json({ | |
hostname: req.hostname, | |
query: req.query, | |
params: req.params | |
}); | |
}); | |
//tells app to listen for requests | |
app.listen(process.env.PORT, () => { | |
console.log(`Listening on port ${process.env.PORT}`); | |
}); | |
//Q: These are undefined but seem to have an inherent function, are they node commands/methods? require, get, req, res, listen, process | |
//Q: Why are we doing this? What does this do? | |
//Q: when we click "show live" it says "cannnot GET" is this the intended result or an error | |
//Q: logs just say listening, when do they show activity? How is Glitch connected to Postman? | |
****MAD LIBS DRILL**** | |
"use strict"; | |
// import express | |
const express = require("express"); | |
// init a new express app | |
const app = express(); | |
// use express middleware to parse the request body and add it to the request object | |
app.use(express.json()); | |
function doMadlib(body) { | |
// we use destructuring to get the values for adjective1, adjective2, etc. | |
// from the request params | |
const { | |
adjective1, | |
adjective2, | |
adjective3, | |
adverb, | |
name, | |
noun, | |
place | |
} = body; | |
// then we return a string that substitutes in these values | |
return ( | |
`There's a ${adjective1} new ${name} in ${place} and everyone's ` + | |
`talking. Stunningly ${adjective2} and ${adverb} ${adjective3}, all the cool kids know it. ` + | |
`However, ${name} has a secret - ${name}'s a vile vampire. \n` + | |
`Will it end with a bite, or with a stake through the ${noun}?` | |
); | |
} | |
// POST requests to the root of the server | |
// Pass params for doMadlib as JSON in the request body | |
app.post("/", (req, res) => res.send(doMadlib(req.body))); | |
// listen for requests :) | |
app.listen(process.env.PORT, () => | |
console.log(`Your app is listening on port ${process.env.PORT}`) | |
); | |
//Q: How do we get the request params? What would that look like? E.g. a form with fields for user input with class names "adjective1", "adjective2", etc that get slipped into the cost above? | |
//Q: Show live is not working, why? Needs an HTML file right? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment