express-1c controllers home-controller.js middleware.js package.json main.js
/express-1c
/express-1c/controllers
>npm init
>npm install http-status-codes express
const codes = require('http-status-codes'), br = '<br>'; const homeFct = (req, res) => { res.type('html') res.status(codes.OK); res.write('Greetings from web app' + br); res.write('Hello from controller'); res.end(); }; exports.homeFct = homeFct;
//middleware.js const middlewareFct = (req, res, nextFct) => { console.log('request received in middleware'); console.log(`url path and query: ${req.url}`); //Run param "nextFct" (and end this function) nextFct(); }; exports.middlewareFct = middlewareFct;
"use strict"; const port = 3000, express = require("express"), hc = require('./controllers/home-controller'), middleware = require('1./controllers/middleware'), app = express(), msg = `Server started on port: ${port}`; const started = () => console.log(msg); //use middleware2app.use(middleware.middlewareFct); //route path "/" to controller's "homeFct" app.get("/", hc.homeFct); //start the web server app app.listen(port, started);
>node main
Server started on port: 3000 request received in middleware url path and query: /