Skip to content

Instantly share code, notes, and snippets.

@iancover
Last active February 5, 2022 12:30
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 iancover/82d62477b97d32a6a321bbd0dacfedf1 to your computer and use it in GitHub Desktop.
Save iancover/82d62477b97d32a6a321bbd0dacfedf1 to your computer and use it in GitHub Desktop.
Basic node server files.
// Example 1: ECHO ENDPOINT
'use strict'
const express = require('express');
const app = express();
app.get('/echo/:what', (req, res) => {
res.json({
host: req.hostname,
path: req.path,
query: req.query,
params: req.params
});
});
app.listen(process.env.PORT, () => {
console.log(`Listening on port ${process.env.PORT}`);
});
/*
*** REQUEST URL ***
https://drill1-echo-endpoint.glitch.me/echo/foo?cats=dogs
*** RESPONSE LOG:
{
"host": "drill1-echo-endpoint.glitch.me",
"path": "/echo/foo",
"query": {
"cats": "dogs"
},
"params": {
"what": "foo"
}
}
*/
// Example 3: A/B Test
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const AB_COOKIE_NAME = 'a-b-test';
app.use(cookieParser());
app.use(express.static('public'));
const assignAb = () => ['a', 'b'][Math.floor(Math.random() * 2)];
app.get('/', (req, res) => {
const cookie = req.cookies[AB_COOKIE_NAME];
console.log(req.cookies.constructor);
if (cookie === undefined) {
res.cookie(AB_COOKIE_NAME, assignAb(), {});
}
res.sendFile(__dirname + '/views/index.html');
});
// Example 2: MAD LIB
const express = require('express');
const app = express();
const doMadlib = (params) => {
const {adjective1, adjective2, adjective3, adverb, name, noun, place} = params;
return (
`There's a ${adjective1} new ${noun} 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}'s heart?`
);
};
app.get('/', (req, res) => res.send(doMadlib(req.query)));
@iancover
Copy link
Author

Drills done on Thinkful using Glitch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment