Node.js Notes February


February 1, 2021

1. Create package.json in Node.js

npm init
npm install nodemon --save-dev
npm install express

2. Core Node.js Modules Exist

Examples include http, https, fs

const http = require('http') to import. Nothing needs to be installed since its a core package included with Node.js.

3. Middleware Example

const app = express();

app.use('/users', (req, res, next) => {
    console.log('In another middleware');
   // next();
   res.send('users');
});

app.use('/', (req, res, next) => {
   console.log('keep going!');
   res.send('hi there!!!').status(200);
});

4. body-parser

npm install body-parser --save

Save it with --save because we want to have it in production. body-parser gets added and removed in Node.js so its best practice to download it via third party.

February 3, 2021

1. Express has a Router function. This can be used to seperate routes.

Admin.js File

const express = require('express');
const router = express.Router();

router.get('/add-product', (req, res, next) => {
    console.log('In another middleware');
   res.send('<form action="/product" method="POST">
   <input type="text" name="title" />
   <button type="submit">Add Product</button></form>');
});

router.post('/product', (req, res, next) => {
    console.log(req.body);
    console.log(req.body.title);
    res.send('<h1>hi there!!!</h1>').status(200);
 });

 module.exports = router;

app.js File

const adminRoutes = require('./routes/admin');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
app.use(adminRoutes);

2. Create a 404 Page

// Put 404 page at very end
app.use((req, res, next) => {
   res.status(404).send('<h1>Page not Found!!</h1>')
});

3. Filtering Paths

To append /admin at the beginning of every route:

app.use('/admin', adminRoutes);
http://localhost:9000/admin/add-product

4. Serving up Files using path.join.

5. Using a rootDir for paths

Make path.js in util folder

const path = require('path');
module.exports = path.dirname(process.mainModule.filename);

February 4, 2021

Statically Serving the public folder

Add in this code snippet to allow files to be statically hosting from the public folder.

Using a Template Rendering Engine

EJS, Pug, and Handlebars are examples of template rendering engines that express.js can use. React is another one.

npm install --save ejs pug express-handlebars

Comments

Popular posts from this blog

Palo Alto for GNS3 CCDC Tutorial

Trace Labs Global Missing Persons CTF V

Release of CCDC ISE Manager Website