ExpressJS
Introduction
const express = require("express");
const path = require("path");
const app = express();
// define middleware to parse body of request
// usally used for rest api, as the content-type is mainly application/json
// for parsing the request body as json
app.use(express.json());
// used to parse form data, as the content type is mainly
// application/x-www-form-urlencoded
app.use(express.urlencoded({extended: false});
// override the query parser setting, the default value is "extended"
// however, the default depth of qs is 5, so needed to be increased when needed
app.set('query parser', (queryString) => {
const qs = require('qs');
return qs.parse(queryString, {
depth: 100, // Increase depth limit from default 5
arrayLimit: 100, // Optional: increase array items limit
parameterLimit: 2000, // Optional: increase parameter count limit
});
});
// server static file, such as image
app.use(express.static(path.join("__dirname","public")));
// defining middleware globally
app.use((req,res,next)=>{
console.log("middleware 1");
// go to next middleware
next();
});
app.use((req,res,next)=>{
console.log("middleware 2");
next();
});
// only applicable to "/halo" path
app.use("/halo",(req,res,next)=>{
console.log("halo");
});
// only applicable to "/halo" path
app.use("/halo/:id",(req,res,next)=>{
console.log("halo",req.params.id);
});
app.use("/halo",(req,res,next)=>{
console.log("halo");
});
// only applicable for post method and path "/post"
app.post("/post", (req,res,next)=>{
console.log(req.body);
});
// The code behind is to create http server, ...
app.listen(8080, function () {
console.log("Server Start ");
});Separating Routes
Error Handling
Template Engine
Session & Cookie
Flash message
CSRF Token
File Handling
Upload
Download
Deployment
Pre-action
Https
Forever
Last updated



