What is Express.js?
ExpressJS is a Nodejs based web application Framework. It provides a robust set of features for web apps and Mobile applications
What are the important features of Express.js?
- It is a Light weight framework
- It is Server side web and mobile application framework
- It is written in JavaScript language
- It supports routing
- It builds single page, multipage, hybrid mobile and web applications and also common back end functions for web applications
- Express comes with two templating engines, Jade and EJS, which facilitate the flow of data into a website structure.
- It supports MVC pattern
- It’s cross-platform, so it’s not limited to one OS.
- You can create complex applications using the express generator.
Why use Express.js?
Express helps you respond to requests with route support so that you may write responses to specific URLs
It supports multiple templating engines to simplify generating HTML.
It is its very simple and it’s open-source
What is Express Generator?
Express Generator is also a Node JS Module. It is used to quick start and develops Express JS applications very easily. It does not come as part of Node JS Platform basic installation. We need to install it manually.
Explain Middleware in Express.js?
A function that is invoked by the Express routing layer before the final request handler
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
An Express application can use the following types of middleware:
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
- Application-level middleware:
This kind of middleware method is bind to the app Object using app.use() method.
//This middleware will execute for each route.
app.use(function (req, res, next) {
console.log('Current Time:', Date.now())
next()
})
- Router-level middleware:
Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router()
- Error-handling middleware
Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
4.Built-in middleware:
Starting with version 4.x, Express no longer depends on Connect.
Express has the following built-in middleware functions:
- express.static serves static assets such as HTML files, images, and so on.
- express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
- express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+
- Third-party middleware:
There are a number of third party middleware, such as body-parser cookie-parser, mongoose and so on.
To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser, body-parser extract the entire body portion of an incoming request stream and exposes it on req.body, The middleware was a part of Express.js earlier but now you have to install it separately.
These can be installed by using command:
>>npm install MODULE_NAME
And they can be loaded using requires and used later.
#Example
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
What are the core features of Express.js?
Allows to set up middleware’s to respond to HTTP Requests
Defines a routing table which is used to perform different actions based on HTTP Method and URL
Allows to dynamically render HTML Pages based on passing arguments to templates
For More:
Write the steps for setting up an Express.js application?
Following are the steps accustomed for An Express JS application: –
A folder with a constant name because the project name is made.
A file named package.json is made within the folder created.
“npm install” command is run on the electronic communication. It installs all the libraries gift in package.json.
A file named server.js is made.
“Router” file is made within the package that consists of a folder named index.js.
“App” is made within the package that has the index.html file.
What are the method responses?
The methods on the response object (res) in the following list can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
- download():Prompt a file to be downloaded.
- end():End the response process.
- json():Send a JSON response.
- jsonp():Send a JSON response with JSONP support.
- redirect():Redirect a request.
- render():Render a view template.
- send():Send a response of various types.
- sendFile():Send a file as an octet stream.
- sendStatus():Set the response status code and send its string representation as the response body.
Explain Database integration in Express.js?
Adding the capability to connect databases to Express apps is just a matter of loading an appropriate Node.js driver for the database in your app
Express Js supports many RDBMS & NoSQL Database like
Read: Node.js Interview Questions and Answers
How to Redirect 404 Errors to a Page in Express.js?
In server.js add the subsequent code to send 404 errors back to a page in our ExpressJS App:
/* Define fallback route */
app.use(function(req, res, next) {
res.status(404).json({errorCode: 404, errorMsg: “route not found”});
});
How to do 404 Errors?
By using below code:
app.get(‘*’, function(req, res){
res.send(‘what???’, 404);
});
How to enable debugging in express app?
In different Operating Systems, we have following commands:
On Linux:
DEBUG=express:*
node app.js
On Windows:
set DEBUG=express:*
node app.js
What function are arguments available to Express route handlers?
The arguments which are available to an Express JS route handler-function are-
- Req – the request object
- Res – the response object
- Next (optional) – a function that is employed to pass management to 1 of the following route handlers.
The third argument is optional and should be omitted, however, in some cases, it’s helpful wherever there’s a series of handlers and management will be passed to 1 of the following route handlers skipping this one.
How to remove debugging from an Express.js App?
By using below code:
var io = require(‘socket.io’).listen(app, { log: false });
io.set(‘log level’, 1);
How to allow CORS in Express JS? Explain with an example?
In order to permit CORS in Express.js, add the subsequent code in server.js:
For Example –
app.all(‘*’, function(req, res, next) {
res.set(‘Access-Control-Allow-Origin’, ‘*’);
res.set(‘Access-Control-Allow-Methods’, ‘GET, POST, DELETE, PUT’);
res.set(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type’);
if (‘OPTIONS’ == req.method) return res.send(200);
next();
});
What is the use of NEXT t in Express.js?
Next -It passes management to a consecutive matching route. OR a operate to pass management to 1 of the following route handlers.
The argument could also be omitted, however, is beneficial in cases wherever you have got a series of handlers and you’d wish to pass management to 1 of the following route handlers, and skip this one.
app.get(‘/user details/:id?’, function(req, res, next));
Req and Res – It represents the request and response objects
Next – It passes management to a consecutive matching route.
How to get the full URL in Express.js?
By using below code:
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + ‘://’ + req.host + ( port == 80 || port == 443 ? ” : ‘:’+port ) + req.path;
How to Config properties in Express.js?
In Express JS, there are 2 ways that for configuring the properties:
With process.ENV:
A file with the name “.env” is to be created within the project folder.
All the properties are to be other within the “.env” file.
Any of the properties will be employed in server.js.
With require.JS:
A file with the name “config.json” is to be created within the config folder within the project folder.
The config properties are to be present within the config.json file.
Now, ought to be accustomed access the config.json file.
How to get post a Query in Express.js?
var bodyParser = require(‘body-parser’)
app.use( bodyParser.json() ); // to support JSON-encoded
app.use(bodyParser.urlencoded({ // to support URL-encoded
extended: true
}));
How to Download a File?
By using below code:
app.get(‘/download’, function(req, res){
var file = __dirname + ‘/download
How to create an HTTP server using Express?
Express is best for developing web application using Node.js. You can create an http server using express as given below:
var express = require(“express” );
var app = express();
app.get( “/”, function (req, res) {
res.write(“Hello, Express”);
res.end();
});
var port = process.env.port || 1305;
app.listen(port);
console.log(“Server is running at http://localhost:” + port);
What template engines you can use with express?
The popular template engines which you can use with Express are Pug, Handlebars, Mustache, and EJS. The Express application generator uses Pug as its default template engine.
How to install Expressjs?
Assuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.
$ mkdir myapp
$ cd myapp
Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.
$ npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.
Now install Express in the myapp directory and save it in the dependencies list. For example:
$ npm install express –save
To install Express temporarily and not add it to the dependencies list, omit the –save option:
$ npm install express
Explain Express.js Template Engine?
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.Some popular template engines that work with Express are Pug, Mustache, and EJS. The Express application generator uses Jade as its default, but it also supports several others.