It's been awhile since I've used express so I figure I'll write a new cheatsheet. It'll probably be very similar to the previous one :)
Start the project:
mkdir project
cd project
npm init
Install express:
npm install express
I'm going to be using https as I'll need access to websockets and webrtc.
Create the ssl certficate:
mkdir certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout certs/server.key
-out certs/server.crt
Now we can create our index.js:
const fs = require("fs");
const https = require("https");
const credentials = {
key: fs.readFileSync("certs/server.key"),
cert: fs.readFileSync("certs/server.crt"),
};
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello World");
});
const httpsServer = https.createServer(credentials, app);
const PORT = process.env.PORT || 3000;
httpsServer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
At this point we can navigate to our application running on port 3000. Make sure to use https.
The next thing to add is the ejs templating engine.
npm install ejs
Now update index.js:
const app = express();
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
res.render("index");
});
Now we can create the views folder:
mkdir views
Ejs will look in the views folder for index.ejs, which we can populate with:
Hello from the template.
Now we can restart our application and see that the template is being rendered.