Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Go to ‘https://expressjs.com/’ and explore for more information to know about express. This site has some links to API, express-generator, Guide with some examples. We will be going to cover some of the topics, which will help you to build a better application using express. Also in express.js site, there are advanced topics like template engines, process managers, security and performance with some best practices. Finally, resources are a great place to known and ask for questions.
Let us start with the course which will cover some of the topics like routes, template engine, middleware, body parsing, cookies, authentication etc. This would be good enough to build an express application.
Brand new express application from scratch:
Install express using npm install express –g for globally for the terminal.
Open your IDE which has terminally inbuilt in it like visual studio code. Create a folder express-app which will have all the examples we are going to work on.
Type ‘npm init’ in terminal to generator the package.json which will prompt a few things like version, description and so on. For now, we can continue with default ones.
If you switch to explorer, package.json is generated and open it to see the values are generated.
Now let's install few dependency i.e. npm install –save express nodemon (to watch and refresh server without restarting it)
Since we will code in ES6 syntax, we need to install compilers for conversation.
npm install –save-dev babel-cli babel-preset-evn babel-stage-0
Check the dependencies and dev-dependencies in package.json to make sure they are installed and segregated accordingly.
Now we want to change the scripts section to add a start which will be used to start our server.
“start” : nodemon ./index.js –exec babel-node –e js
Add babel configuration inside a new file .babelrc as shown below to run our ES6 code to compatible code in server
{ “presets”: [“env”, “stage-0”] }
Finally, we need to create an index.js file which we used in start script of package.json. We can name it differently but the same should be used in package.json.
Section 1:[index.js]
Import express from ‘express’; const app = express(); const port = 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Run npm start in the terminal and observe that server is running.
Note: To get mock data in json, we can use https://www.mockaroo.com/ which we are going to serve from the server.
Section 2: Let's extend the express app to add data to the server.
import data from './data/data.json'
console.log(data);
Section 3: Creating a route, which is responsible for getting your page or data requested from the server. There are basically four methods GET, POST, DELETE and PUT. It follows a request-response paradigm.
app.get('/', (req, res) => // get data first res.send(`get request called on PORT: ${PORT}`); );
app.post('/newItem', (req, res) => // get data first res.send(`post request called on PORT: ${PORT}`); ); app.put('/item', (req, res) => // get data first res.send(`put request called on PORT: ${PORT}`); ); app.delete('/item', (req, res) => // get data first res.send(`delete request called on PORT: ${PORT}`); );
Note: We can insert body via POST Man and another cool feature of the postman is ‘code’ option. We get the API calling in our preferred language.
Section 4: Now instead of sending a simple text, let us send some data actually.
app.get('/', (req, res) => // get data first res.json(data) );
Section 5: Some times, we need to serve some static files like CSS, HTML, images etc.
app.use(express.static('public')); For now, think that ‘use’ is a method that allows adding specific middleware.
And app.use('/images', express.static('images'));
Complete code till this point:
importexpressfrom'express'; importdatafrom'./data/data.json'; constapp = express(); constPORT = 3000; // This is for the public folder on path / app.use(express.static('public')); // this is for images folder on path images app.use('/images', express.static('images')); app.get('/', (req, res) => // get data first res.json(data) ); app.post('/newItem', (req, res) => res.send(`post request called on PORT: ${PORT}`); ); app.put('/item', (req, res) => res.send(`put request called on PORT: ${PORT}`); ); app.delete('/item', (req, res) => res.send(`delete request called on PORT: ${PORT}`); ); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); console.log(data); });
Section 6: Route parameters
Till now, we played around with routes without parameters. Now we will extend this example to consider routing parameters.
app.get('/item/:id', (req, res, next) => { // extract the parameters and all parameter are converted to string console.log(req.params.id); // Conversation to number let user = Number(req.params.id); console.log(user); // retrieve the specific user based on id from out mockData. console.log(data[user]); res.send(data[user]); });
Route Handlers:
app.put('/item', (req, res) => res.send(`put request called on PORT: ${PORT}`);
);
app.get('/item/:id', (req, res, next) => { … //previous code next(); }, (req, res) => { console.log(‘Data is returned’); });
app.get('/item/:id', (req, res, next) => { console.log(req.params.id); letuser = Number(req.params.id); console.log(user); console.log(data[user]); res.send(data[user]); next(); }, (req, res) => console.log('Did you get the right data?') );
We have a few common methods on the response object which we need to understand before using them. For example, till this point we used res.send and res.json to return the data from the server. It is important to understand the difference.
For other methods refer to response methods here: http://expressjs.com/en/guide/routing.html
Sometimes we need to have different methods for the same route like app.get(‘/item’), app.put(‘/item’) and app.delete(‘/item’). We can chain all of this together as shown below:
app.route('/item') .get((req, res) => { res.send(`a get request with /item route on port ${PORT}`) }) .put((req, res) => res.send(`a put request with /item route on port ${PORT}`) ) .delete((req, res) => res.send(`a delete request with /item route on port ${PORT}`) );
We are using the app.route method to create chainable route handlers for a route path.
Template engines: Express provides support to a lot of template engines ‘out-of-box’. We can refer to them here - https://expressjs.com/en/resources/template-engines.html
Out of this, some of the most popular are Pug, hbs, ejs. Let’s compare hbs and pugs.
Hbs – syntax is similar to html template just that variables are in double curly braces.
<div class=’entry’> <h 1>{{title}}</h 1> </div> Pub (jade) – is kind of new syntax and uses white space for differentiation. It is lot smaller. .entry h1=title
Let us take any of the above examples and implement templates.
const express = require('express'); const path = require('path'); const app = express(); app.set(‘view engine’, ‘pug’);
app.set(‘views’, path.join(__dirname, ‘./views’));
Since we have given folder path, express assumes that index file exists and loads it accordingly.
doctype html html head body h1 Index Page p This is the index page
app.get(‘/’, (req, res, next) => { return res.render(‘index’); });
app.locals.pretty = true;
res.locals is an object where we can add new fields in specific route and use them in the *.pug file. To illustrate this, let’s use a middleware to listen to error.
app.use((err, req, res, next) => { res.locals.message = err.message; const status = err.status || 500; res.locals.status = status; res.locals.error = err; res.status(status); return res.render('error'); });
[we can convert an existing error page to pug format through some of the online converters]
doctype html html head body h1 Index Page p This is the index page if (error) h1.mr-3.pr-3.align-top.border-right.inline-block.align-content-center=status .inline-block.align-middle h2#desc.font-weight-normal.lead=message pre=error.stack
constexpress = require('express'); constcreateError = require('http-errors'); constpath = require('path'); constapp = express(); app.set('view engine', 'pug'); app.locals.pretty = true; app.set('views', path.join(__dirname, './views')); app.get('/', (req, res, next) => { returnres.render('index'); }); app.use((req, res, next) => { returnnext(createError(404, 'File not found')); }); app.use((err, req, res, next) => { res.locals.message = err.message; conststatus = err.status || 500; res.locals.status = status; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(status); returnres.render('error'); }); app.listen(3000);
JavaScript is a dynamic computer programming language for the web. Jav...
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *