ExpressJS – Useful Resources

ExpressJS – Useful Resources ”; Previous Next The following resources contain additional information on ExpressJS. Please use them to get more in-depth knowledge on this topic. Useful Video Courses ExpressJS Online Training Featured 17 Lectures 1 hours Tutorialspoint More Detail Build a simple chat system in JavaScript 15 Lectures 2.5 hours Musab Zayadneh More Detail Blockchain Course: Learn by Building Your Own In JavaScript Most Popular 74 Lectures 7.5 hours Eric Traub More Detail TypeScript from Scratch: Go from zero to hero in TypeScript 78 Lectures 3.5 hours TELCOMA Global More Detail Build a To-Do List App with Node, Express, React and MongoDB Most Popular 65 Lectures 4 hours Moath Zayadneh More Detail Express JS Fast Learn for Beginner 14 Lectures 1 hours Ricky Muliawan More Detail Print Page Previous Next Advertisements ”;

ExpressJS – Scaffolding

ExpressJS – Scaffolding ”; Previous Next Scaffolding allows us to easily create a skeleton for a web application. We manually create our public directory, add middleware, create separate route files, etc. A scaffolding tool sets up all these things for us so that we can directly get started with building our application. The scaffolder we will use is called Yeoman. It is a scaffolding tool built for Node.js but also has generators for several other frameworks (like flask, rails, django, etc.). To install Yeoman, enter the following command in your terminal − npm install -g yeoman Yeoman uses generators to scaffold out applications. To check out the generators available on npm to use with Yeoman, you can click on this link. In this tutorial, we will use the ”generator-Express-simple”. To install this generator, enter the following command in your terminal − npm install -g generator-express-simple To use this generator, enter the following command − yo express-simple test-app You will be asked a few simple questions like what things you want to use with your app. Select the following answers, or if you already know about these technologies then go about choosing how you want them to be. express-simple comes with bootstrap and jquery [?] Select the express version you want: 4.x [?] Do you want an mvc express app: Yes [?] Select the css preprocessor you would like to use: sass [?] Select view engine you would like to use: jade [?] Select the build tool you want to use for this project: gulp [?] Select the build tool you want to use for this project: gulp [?] Select the language you want to use for the build tool: javascript create public/sass/styles.scss create public/js/main.js create views/layout.jade create views/index.jade create views/404.jade create app.js create config.js create routes/index.js create package.json create bower.json identical .bowerrc identical .editorconfig identical .gitignore identical .jshintrc create gulpfile.js I”m all done. Running bower install & npm install for you to install the required dependencies. If this fails, try running the command yourself. It will then create a new application for you, install all the dependencies, add few pages to your application(home page, 404 not found page, etc.) and give you a directory structure to work on. This generator creates a very simple structure for us. Explore the many generators available for Express and choose the one that fits you right. Steps to working with all generators is the same. You will need to install a generator, run it using Yeoman; it will ask you some questions and then create a skeleton for your application based on your answers. Print Page Previous Next Advertisements ”;

ExpressJS – Error handling

ExpressJS – Error Handling ”; Previous Next Error handling in Express is done using middleware. But this middleware has special properties. The error handling middleware are defined in the same way as other middleware functions, except that error-handling functions MUST have four arguments instead of three – err, req, res, next. For example, to send a response on any error, we can use − app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send(”Something broke!”); }); Till now we were handling errors in the routes itself. The error handling middleware allows us to separate our error logic and send responses accordingly. The next() method we discussed in middleware takes us to next middleware/route handler. For error handling, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example. var express = require(”express”); var app = express(); app.get(”/”, function(req, res){ //Create an error and pass it to the next function var err = new Error(“Something went wrong”); next(err); }); /* * other route handlers and middleware here * …. */ //An error handling middleware app.use(function(err, req, res, next) { res.status(500); res.send(“Oops, something went wrong.”) }); app.listen(3000); This error handling middleware can be strategically placed after routes or contain conditions to detect error types and respond to the clients accordingly. The above program will display the following output. Print Page Previous Next Advertisements ”;

ExpressJS – Discussion

Discuss ExpressJS ”; Previous Next Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It is an open source framework developed and maintained by the Node.js foundation. Print Page Previous Next Advertisements ”;

ExpressJS – Routing

ExpressJS – Routing ”; Previous Next Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. The following function is used to define routes in an Express application − app.method(path, handler) This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type. Path is the route at which the request will run. Handler is a callback function that executes when a matching request type is found on the relevant route. For example, var express = require(”express”); var app = express(); app.get(”/hello”, function(req, res){ res.send(“Hello World!”); }); app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route “/hello”, our Express app executes the callback function attached to this route and sends “Hello World!” as the response. We can also have multiple different methods at the same route. For example, var express = require(”express”); var app = express(); app.get(”/hello”, function(req, res){ res.send(“Hello World!”); }); app.post(”/hello”, function(req, res){ res.send(“You just called the post method at ”/hello”!n”); }); app.listen(3000); To test this request, open up your terminal and use cURL to execute the following request − curl -X POST “http://localhost:3000/hello” A special method, all, is provided by Express to handle all types of http methods at a particular route using the same function. To use this method, try the following. app.all(”/test”, function(req, res){ res.send(“HTTP method doesn”t have any effect on this route!”); }); This method is generally used for defining middleware, which we”ll discuss in the middleware chapter. Routers Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we will use Express.Router. Create a new file called things.js and type the following in it. var express = require(”express”); var router = express.Router(); router.get(”/”, function(req, res){ res.send(”GET route on things.”); }); router.post(”/”, function(req, res){ res.send(”POST route on things.”); }); //export this router to use in our index.js module.exports = router; Now to use this router in our index.js, type in the following before the app.listen function call. var express = require(”Express”); var app = express(); var things = require(”./things.js”); //both index.js and things.js should be in same directory app.use(”/things”, things); app.listen(3000); The app.use function call on route ”/things” attaches the things router with this route. Now whatever requests our app gets at the ”/things”, will be handled by our things.js router. The ”/” route in things.js is actually a subroute of ”/things”. Visit localhost:3000/things/ and you will see the following output. Routers are very helpful in separating concerns and keep relevant portions of our code together. They help in building maintainable code. You should define your routes relating to an entity in a single file and include it using the above method in your index.js file. Print Page Previous Next Advertisements ”;

ExpressJS – Database

ExpressJS – Database ”; Previous Next We keep receiving requests, but end up not storing them anywhere. We need a Database to store the data. For this, we will make use of the NoSQL database called MongoDB. To install and read about Mongo, follow this link. In order to use Mongo with Express, we need a client API for node. There are multiple options for us, but for this tutorial, we will stick to mongoose. Mongoose is used for document Modeling in Node for MongoDB. For document modeling, we create a Model (much like a class in document oriented programming), and then we produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these “documents”, then finally, we will write these documents in our database. Setting up Mongoose Now that you have installed Mongo, let us install Mongoose, the same way we have been installing our other node packages − npm install –save mongoose Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter “mongo”. A Mongo shell will start, enter the following code − use my_db A new database will be created for you. Whenever you open up the mongo shell, it will default to “test” db and you will have to change to your database using the same command as above. To use Mongoose, we will require it in our index.js file and then connect to the mongodb service running on mongodb://localhost. var mongoose = require(”mongoose”); mongoose.connect(”mongodb://localhost/my_db”); Now our app is connected to our database, let us create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any route − var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model(“Person”, personSchema); The above code defines the schema for a person and is used to create a Mongoose Mode Person. Saving Documents Now, we will create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file called person.pug in views directory with the following content − html head title Person body form(action = “/person”, method = “POST”) div label(for = “name”) Name: input(name = “name”) br div label(for = “age”) Age: input(name = “age”) br div label(for = “nationality”) Nationality: input(name = “nationality”) br button(type = “submit”) Create new person Also add a new get route in index.js to render this document − app.get(”/person”, function(req, res){ res.render(”person”); }); Go to “localhost:3000/person” to check if the form is displaying the correct output. Note that this is just the UI, it is not working yet. The following screenshot shows how the form is displayed − We will now define a post route handler at ”/person” which will handle this request app.post(”/person”, function(req, res){ var personInfo = req.body; //Get the parsed information if(!personInfo.name || !personInfo.age || !personInfo.nationality){ res.render(”show_message”, { message: “Sorry, you provided worng info”, type: “error”}); } else { var newPerson = new Person({ name: personInfo.name, age: personInfo.age, nationality: personInfo.nationality }); newPerson.save(function(err, Person){ if(err) res.render(”show_message”, {message: “Database error”, type: “error”}); else res.render(”show_message”, { message: “New person added”, type: “success”, person: personInfo}); }); } }); In the above code, if we receive any empty field or do not receive any field, we will send an error response. But if we receive a well-formed document, then we create a newPerson document from Person model and save it to our DB using the newPerson.save() function. This is defined in Mongoose and accepts a callback as argument. This callback has 2 arguments – error and response. These arguments will render the show_message view. To show the response from this route, we will also need to create a show_message view. Create a new view with the following code − html head title Person body if(type == “error”) h3(style = “color:red”) #{message} else h3 New person, name: #{person.name}, age: #{person.age} and nationality: #{person.nationality} added! We will receive the following response on successfully submitting the form(show_message.pug) − We now have an interface to create persons. Retrieving Documents Mongoose provides a lot of functions for retrieving documents, we will focus on 3 of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are as follows − Model.find(conditions, callback) This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example, Person.find(function(err, response){ console.log(response); }); This will fetch all the documents from the person”s collection. Person.find({name: “Ayush”, age: 20}, function(err, response){ console.log(response); }); This will fetch all documents where field name is “Ayush” and age is 20. We can also provide projection we need, i.e., the fields we need. For example, if we want only the names of people whose nationality is “Indian”, we use − Person.find({nationality: “Indian”}, “name”, function(err, response){ console.log(response); }); Model.findOne(conditions, callback) This function always fetches a single, most relevant document. It has the same exact arguments as Model.find(). Model.findById(id, callback) This function takes in the _id(defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example, Person.findById(“507f1f77bcf86cd799439011″, function(err, response){ console.log(response); }); Let us now create a route to view all people records − var express = require(”express”); var app = express(); var mongoose = require(”mongoose”); mongoose.connect(”mongodb://localhost/my_db”); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model(“Person”, personSchema); app.get(”/people”, function(req, res){ Person.find(function(err, response){ res.json(response); }); }); app.listen(3000); Updating Documents Mongoose provides 3 functions to update documents. The functions are described below − Model.update(condition, updates, callback) This function takes a conditions and updates an object as input and applies the changes to all the documents matching the conditions in the collection. For example, following code

ExpressJS – Debugging

ExpressJS – Debugging ”; Previous Next Express uses the Debug module to internally log information about route matching, middleware functions, application mode, etc. To see all internal logs used in Express, set the DEBUG environment variable to Express:* when starting the app − DEBUG = express:* node index.js The following output will be displayed. These logs are very helpful when a component of your app is not functioning right. This verbose output might be a little overwhelming. You can also restrict the DEBUG variable to specific area to be logged. For example, if you wish to restrict the logger to application and router, you can use the following code. DEBUG = express:application,express:router node index.js Debug is turned off by default and is automatically turned on in production environment. Debug can also be extended to meet your needs, you can read more about it at its npm page. Print Page Previous Next Advertisements ”;

ExpressJS – Best Practices

ExpressJS – Best Practices ”; Previous Next Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn”t have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications. First, we will discuss the best practices for creating node and Express applications. Always begin a node project using npm init. Always install dependencies with a –save or –save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies. Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase. Don’t push node_modules to your repositories. Instead npm installs everything on development machines. Use a config file to store variables Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page. Directory Structure Let us now discuss the Express’ Directory Structure. Websites Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website. test-project/ node_modules/ config/ db.js //Database connection and configuration credentials.js //Passwords/API keys for external services used by your app config.js //Other environment variables models/ //For mongoose schemas users.js things.js routes/ //All routes for different entities in different files users.js things.js views/ index.pug 404.pug … public/ //All static content being served images/ css/ javascript/ app.js routes.js //Require all routes in this and then require this file in app.js package.json There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links. https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs–net-34168 and, https://www.terlici.com/2014/08/25/best-practices-express-structure.html. RESTful APIs APIs are simpler to design; they don”t need a public or a views directory. Use the following structure to build APIs − test-project/ node_modules/ config/ db.js //Database connection and configuration credentials.js //Passwords/API keys for external services used by your app models/ //For mongoose schemas users.js things.js routes/ //All routes for different entities in different files users.js things.js app.js routes.js //Require all routes in this and then require this file in app.js package.json You can also use a yeoman generator to get a similar structure. Print Page Previous Next Advertisements ”;

ExpressJS – URL Building

ExpressJS – URL Building ”; Previous Next We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. Here is an example of a dynamic route − var express = require(”express”); var app = express(); app.get(”/:id”, function(req, res){ res.send(”The id you specified is ” + req.params.id); }); app.listen(3000); To test this go to http://localhost:3000/123. The following response will be displayed. You can replace ”123” in the URL with anything else and the change will reflect in the response. A more complex example of the above is − var express = require(”express”); var app = express(); app.get(”/things/:name/:id”, function(req, res) { res.send(”id: ” + req.params.id + ” and name: ” + req.params.name); }); app.listen(3000); To test the above code, go to http://localhost:3000/things/tutorialspoint/12345. You can use the req.params object to access all the parameters you pass in the url. Note that the above 2 are different paths. They will never overlap. Also if you want to execute code when you get ”/things” then you need to define it separately. Pattern Matched Routes You can also use regex to restrict URL parameter matching. Let us assume you need the id to be a 5-digit long number. You can use the following route definition − var express = require(”express”); var app = express(); app.get(”/things/:id([0-9]{5})”, function(req, res){ res.send(”id: ” + req.params.id); }); app.listen(3000); Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you”ll get a “Cannot GET <your-request-route>” message as response. This message be replaced by a 404 not found page using this simple route − var express = require(”express”); var app = express(); //Other routes here app.get(”*”, function(req, res){ res.send(”Sorry, this is an invalid URL.”); }); app.listen(3000); Important − This should be placed after all your routes, as Express matches routes from start to end of the index.js file, including the external routers you required. For example, if we define the same routes as above, on requesting with a valid URL, the following output is displayed. − While for an incorrect URL request, the following output is displayed. Print Page Previous Next Advertisements ”;

ExpressJS – Quick Guide

ExpressJS – Quick Guide ”; Previous Next ExpressJS – Overview ExpressJS is a web application framework that provides you with a simple API to build websites, web apps and back ends. With ExpressJS, you need not worry about low level protocols, processes, etc. What is Express? Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express. Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and numerous open source contributors. Why Express? Unlike its competitors like Rails and Django, which have an opinionated way of building applications, Express has no “best way” to do something. It is very flexible and pluggable. Pug Pug (earlier known as Jade) is a terse language for writing HTML templates. It − Produces HTML Supports dynamic code Supports reusability (DRY) It is one of the most popular template language used with Express. MongoDB and Mongoose MongoDB is an open-source, document database designed for ease of development and scaling. This database is also used to store data. Mongoose is a client API for node.js which makes it easy to access our database from our Express application. ExpressJS – Environment In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node –version npm –version You should get an output similar to the following. v5.0.0 3.5.2 Now that we have Node and npm set up, let us understand what npm is and how to use it. Node Package Manager(npm) npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS. How to use npm? There are two ways to install a package using npm: globally and locally. Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code. npm install -g <package-name> Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag. npm install <package-name> Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project. Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it − Step 2 − Now to create the package.json file using npm, use the following code. npm init It will ask you for the following information. Just keep pressing enter, and enter your name at the “author name” field. Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command − npm install –save express To confirm that Express has installed correctly, run the following code. ls node_modules #(dir node_modules for windows) Tip − The —save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us. This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command − npm install -g nodemon You can now start working on Express. ExpressJS – Hello World We have set up the development, now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it. var express = require(”express”); var app = express(); app.get(”/”, function(req, res){ res.send(“Hello world!”); }); app.listen(3000); Save the file, go to your terminal and type the following. nodemon index.js This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot. How the App Works? The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app. app.get(route, callback) This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request. res.send() This function takes an object as input and it sends this to the requesting client. Here we are sending the string “Hello World!”. app.listen(port, [host], [backlog], [callback]]) This function binds and listens for connections on the specified host and port. Port is the only required parameter here. S.No. Argument