Express.js

node.js

Hyerang Raina Kim
4 min readAug 18, 2020

What is Express.js?

express

Alternatives?

  • Vanilla Node.js
  • Adonis.js
  • Koa
  • Sails.js

Using command

>>> npm install --save express

we are now installing express.js framework.

Why did we omit -dev❓

It is the production dependency. We are not just using this framework as a tool during development but rather as an integral part of our application. It should be running when deployed.

Now import the expess.js in app.js and execute it!!

const express = require('express');const app = express()

Then, we pass the app into the createServer parameter!

const server = http.createServer(app);

What’s next? 😊 NPM START 😊

It’ll literally create a server but won’t do anything yet. It sets up a certain way of handling incoming requests that define the key characteristics of express.js!

Middleware

const app = express();app.use((req, res, next) => {
console.log('In the middleware!');
next(); // Allows the request to continue to the next middleware in line
});
app.use('/', (req, res, next) => {
console.log('In another middleware!')
res.send('<h1>Hello from Express!</h1>');
});
const server = http.createServer(app);server.listen(3000);
  • use() allows to add a new middleware function, and it takes the path as its first parameter, which path written is the entire path but has to be started with.
  • next is a function that has to be executed to allow the request to travel on to the next middleware.

Also, we can shorten creating a server code.

app.listen(3000);

Parsing Incoming Requests

We can add another path above

app.use('/add-product', (req, res, next) => {    res.send('<form action="/product" method="POST"><input type="text" name="title"><button type="submit">Add Product</button></form>');});app.use('/product', (req,res,next) => {    console.log(req.body);
res.redirect('/');
});

In console, it’ll return undefined because request doesn’t try to parse the incoming request body. We need to register a parser by adding another middleware before our route handling middleware because parsing of the body should be done no matter where the request ends up.

>>> npm install --save body-parser

Then we need to import the installed package at the top:

const bodyParser = require('body-parser');

Add a new middleware.

app.use(bodyParser.urlencoded({extended : false}));
  • urlencoded(): registers a middleware, so this function yields us such a middleware function and this package calls the next in the end so that it reaches the rest of the middleware, but before it does that, it will do the whole body parsing.

Then in the console, we’ll see

>>> { title: 'Book'}

✔️ Notes!

  • Alternative for app.use() of GET request is app.get()
  • Alternative for app.use() of POST request is app.post()

Express Router

Now we’re splitting up the middleware based on its functionalities. Just create a new folder name routes and create new js files: admin.js and shop.js.

admin.js

const express = require('express');const Router = express.Router();router.get('/add-product', (req, res, next) => {    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);
res.redirect('/');
});module.exports = router;

Router is like a mini express app, tied to the other express app, which we can export in the end.

Importing admin.js in app.js:

const adminRoutes = require('./routes/admin');

Then we need to call in a new middleware.

IMPORTANT!! Order matters!

app.use(adminRoutes);

It needs to come right after body parsing middleware.

Adding a Status Code

app.use((req, res, next) => {
res.status(404).send('<h1>Page not found</h1>');
});

Filtering Path

In app.js, we can add

app.use('./admin', adminRoutes);

So the express.js automatically omits ‘./admin’ in admin.js path, ‘/add-product’, and it matches ‘./admin/add-product’.

Serving HTML Pages

Create a folder name views and put html files in it.

shop.js

router.get('/', (req,res,next) => {
res.sendFile('/views/shop.html');
});

It’ll not work because ‘/’ stands for the root path of the operating system, not this project’s root path.

So, in order to put the absolute path,

const path = require('path');

it will give us a solution!!

router.get('/', (req,res,next) => {
res.sendFile(path.join(__dirname, '../', 'views', 'shop.html'));
});
  • __dirname: global variable made available by node.js simply holds the absolute on our operating system to this project folder.

We can also make a new separate folder name util and put path.js that could replace __dirname, ‘../’.

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

Then in admin.js and shop.js, import path like below,

const rootDir = require('../util/path');

and replace it like shown below.

res.sendFile(path.join(rootDir, 'views', 'add-product.html'))

Serving Files Statically

We add

app.use(express.static(path.join(__dirname,'public')));

in app.js so that it makes public folder accessible to anyone.

--

--

No responses yet