Vincent A Saulys' Blog
ExpressJS Cheat Sheet
Tags: javascript
July 10, 2021

Made this for myself and figured others may find it valuable

// npm i express csurf cookie-parser morgan multer compression

// organization of a project
const express = require("express");
const compression = require("compression");
const cookieParser = require("cookie-parser");
const csrf = requrie("csurf");
const morgan = require("morgan");
const multer = require("multer");

const app = express();

app.use(express.json()); // if using ExpressJS
app.use(cookieParser());
app.use(morgan("tiny")); // common, dev, short tiny
app.use(compression());  // compress all responses

/*
  Create an upload middleware for multer 
  Form must have enctype="multipart/form-data"

  upload.single("nameOfInputFieldWithFileType"); 
  upload.array("nameOf"); <input type="file" name="nameOf" multiple/>
  upload.fields([{name: "something", maxCount: 1}]);
*/
const upload = multer({ dest: "upload/" }); 

app.use("/static", path.join(__dirname, "static"));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

const router = express.Router();
const csrfProtection = csrf({ cookie: true });  // cross-site request forgery

// router.post, router.put, router.delete(),
router.get("/:exampleParam", csrfProtection, async (req, res, next) => {
  // request parameters
  const { exampleParam } = req.params;
  const { someQuery } = req.queries; // will be '123' in /myParam?someQuery=123
  const { val1, val2 } = req.body; // only in app.post(...) after express.json()
  req.cookies; // if cookie-parser is used above
  req.cookies._myCookie = "new value"; // or req.cookie("_myCookie", "new value");

  // responses
  res.header("Access-Control-Allow-Origin", "*"); // example
  res.status(500).send("Some text"); // won't return automatically
  res.json({ msg: "my response" }); // return json data
  res.redirect(301, "http://vincentsaulys.com/"); // redirect
  res.render("name_of_template_in_folder", { msg: "other params" });
  res.download(path.join(__dirname, "some_path")); // returns a file to client
  res.attachment(...); // Content-Disposition: attachment
  res.sendFile(...); // Content-Type is set to file extension

  next(); // only used in middleware
});

// module.exports = router;
app.use("/myRoute", router); // all routes to router will be prefixed with /myRoute

if (process.env.NODE_ENV === "dev") {
  app.listen(3000, async () => { console.log("running at port 3000"); });
} else {
  module.exports = app;
}
Share on...