The goal of this recurring exercise is to quickly scaffold a JavaScript server from memory without the aid of documentation or notes.
Regularly practice creating the following three types of express apps:
- An express app that provides a basic web server using middleware to serve static content.
- An express app that uses routing to return a response from a requested resource.
- An express app with an idiomatic folder structure found in larger express servers.
In the terminal, create a folder in your projects folder called express-drills
to store your express apps.
$ mkdir ~/oca/express-drills
Then, to create an express app:
$ cd ~/oca/express-drills
$ mkdir <project_name>
$ cd express-[0-9]
$ npm init
Add the dependency:
$ npm install express
Then alternate writing out an express server in one of the following formats. You should avoid copy pasting the code and instead type it out manually each time. Remember that the purpose of the exercise is to get better at writing code from memory.
Create an empty file named server.js
and enter the following code from memory (or by copying as needed):
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, function() {
console.log('The EXPRESS server is listening on port 3000.');
});
When you are done writing it, run it using:
$ node server.js
and then using your browser, ensure that it works: http://localhost:3000.
Now, delete all your code and try it again from memory.
Create an empty file named server.js
and enter the following code from memory (or by copying as needed):
const express = require('express');
const app = express();
app.get('/', function(req, res) {
res.status(200).send('Hello World!');
});
app.listen(3000, function() {
console.log('The EXPRESS server is listening on port 3000.');
});
When you are done writing it, run it using:
$ node server.js
and then using your browser, ensure that it works: http://localhost:3000.
Now, delete all your code and try it again from memory.
Add dependency:
$ npm install morgan
Create a new directory and two empty files named index.js
and app.js
and enter the following code from memory (or by copying as needed):
server/app.js
// file: server/app.js
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', function(req, res) {
res.status(200).send('Hello World!');
});
module.exports = app;
server/index.js
// file: server/index.js
const server = require('app');
server.listen(3000, function() {
console.log('The EXPRESS server is listening on port 3000.');
});
When you are done writing it, run it using:
$ node server/index.js
and then using your browser, ensure that it works: http://localhost:3000.
Now, delete all your code and try it again from memory.