Skip to main content

ExpressJS

What is expressJS?
Answer : Express is a relatively small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing; it adds helpful utilities to Node.js’s HTTP objects; it facilitates the rendering of dynamic HTML views; it defines an easily implemented  extensibility standard. This book explores those features in a lot more depth, so all of that lingo will be demystified soon.

What Express is used for ?
Answer : In theory, Express could be used to build any web application. It can process incoming requests and respond to them,
so it can do things that you can do in most of the other frameworks mentioned earlier.

Express is often used to power single-page applications (SPAs). SPAs are very JavaScript-heavy on the front end, and they usually require a server component.
The server is usually required to simply serve the HTML, CSS, and JavaScript, but there’s often a REST API, too. Express can do both of these things quite well; it’s great at serving HTML and other files, and it’s great at building APIs. Because the learning curve is relatively low for front-end developers, they can whip up a simple SPA server with little new learning required.

List Express key features?
Answer : Middleware which is a way to break your app into smaller bits of behavior. Generally, middleware is called one by one, in a sequence.
Routing similarly breaks your app up into smaller functions that are executed when the user visits a particular resource; for example, showing the homepage when the user requests the homepage URL.
Routers can further break up large applications into smaller, composable subapplications.

Question : List major feature of expressJs?
Answer : At a high level, Express provides four major features:
Middleware —In contrast to vanilla Node, where your requests flow through only one function, Express has a middleware stack, which is effectively an array of functions.

Routing —Routing is a lot like middleware, but the functions are called only when you visit a specific URL with a specific HTTP method. For example, you could only run a request handler when the browser visits yourwebsite.com/about.

Extensions to request and response objects —Express extends the request and response objects with extra methods and properties for developer convenience.
Views —Views allow you to dynamically render HTML. This both allows you to change the HTML on the fly and to write the HTML in other languages.

What is the middleware to be used for responding with the static content.
Answer : It’s common for web applications to need to send static files over the wire. These include things like images or CSS or HTML—content that isn’t dynamic.
express.static ships with Express and helps you serve static files. The simple act of sending files turns out to be a lot of work, because there are a lot of edge cases and performance considerations to think about. Express to the rescue!
e.g.
app.use(express.static(path.join(__dirname, 'public')));
const
staticPath = path.join(__dirname, "static");
app.use(express.static(staticPath));


What’s all that business about path.resolve? Why can’t you just say /public? 
Answer : The short answer is that you could, but it’s not cross-platform.
On Mac and Linux, you want this directory:
/public
But on Windows, you want this directory:
\public
Node’s built-in path module will make sure that things run smoothly on Windows, Mac, and Linux.

Question : What is app.use()?
Answer : this is to use any middleware we want to include along with the express?

Question : Do you have example of any custom middleware?
Answer : create a file middleware/myMiddleWare.js (foldername is optional)

const showPath = ( req,res, next) =>{
   
console.log("PATH : "+req.path);
   
next();
}
module.
exports = showPath;


Now go to the app.js, add the dependency

const myMiddleWare = require('./middleware/myMiddleWare');
..
..
..
app.use(myMiddleWare);

Note : The order of middleware loading is important, middleware functions that are loaded first are also executed first, and any middleware which sends the response should not call the next function, i.e. it has to be last middleware to be called.

Question : can we create multiple middleware from single middleware?
Answer :
const showPath = ( req,res, next) =>{
   
console.log("PATH : ",req.path);
   
next();
}
const requestTime = ( req,res, next) =>{
   
console.log("TIME : ",new Date());
   
next();
}
module.
exports = [showPath, requestTime ];


Question : How to create Configurable middleware?
Answer : If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.

module.exports = function (options) {
   
return function (req, res, next) {
       
console.log(options.message || "Default Hello")
        next()
;
   
}
}


The middleware can now be used as shown below.

const myMiddleWare = require('./myMiddleWare.js')
app.
use(myMiddleWare({ message: 'Hi How are You?'}));


Question : Name couple of basic middleware and usage
Answer : connect-ratelimit —Lets you throttle connections to a certain number of requests per hour. If someone is sending numerous requests to your server, you can start giving them errors to stop them from bringing your site down.
Helmet —Helps you add HTTP headers to make your app safer against certain kinds of attacks. We’ll explore it in later chapters. (I’m a contributor to Helmet, so I definitely recommend it!)
cookie-parser —Parses browser cookies.
response-time —Sends the X-Response-Time header so you can debug the performance of your application.

How can you set the view engine, like handlebars, jade, ejs?
Answer : We need to use the app.set with the property "views"
E.g.
// Setting the view Engine
//Location of the view folder
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');


Why use npm start?
Answer : Why use npm start at all—why don’t you run node app.js instead? There are three reasons you might do this.
It’s a convention. Most Node web servers can be started with npm start, regardless of the project’s structure.
If instead of app.js someone had chosen application.js, you’d have to know about that change. The Node community seems to have settled on a common convention here.
It allows you to run a more complex command (or set of commands) with a relatively simple one. Your app is pretty simple now, but starting it could be more complex in the future. Perhaps you’ll need to start up a database server or clear a giant log file. Keeping this complexity under the blanket of a simple command helps keep things consistent and more pleasant.
The third reason is a little more nuanced. npm lets you install packages globally, so you can run them just like any other terminal command. Bower is a common one, letting you install front-end dependencies from the command line with the bower command. You install things like Bower globally on your system. npm scripts allow you to add new commands to your project without installing them globally, so that you can keep all of your dependencies inside your project, allowing you to have unique versions per project. This comes in handy for things like testing and build scripts, as you’ll see down the line.

Question : Give A simple routing example
Answer : var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', (req, res, next)=> {
  res.render('index', { title: req.params.title || "World" });
});
//important steps else it is not available to the apps
module.exports = router;

In your app.js
const index = require('./routes/index');
...
...
...
app.use(index);

Question : Give simple example of all the method call?
Answer :
const express = require('express');
const
router = express.Router();
router.get('/:userName', (req, res, next) => {
    res.
render('index', {title: req.params.userName || "World"});
});
router.post('/', (req, res, next) => {
    res.
json({message : req.body.message});
});
router.put('/', (req, res, next) => {
    res.
send('PUT Response');
});
router.delete('/', (req, res, next) => {
    res.
send('Delete Response');
});
router.patch('/', (req, res, next) => {
    res.
send('Patch Response');
});
router.patch('/', (req, res, next) => {
    res.
send('Patch Response');
});
router.copy('/', (req, res, next) => {
    res.
send('Copy Response');
});
router.options('/', (req, res, next) => {
    res.
send('Options Response');
});
module.exports = router;


Question : Example of Path Variable?
Answer : 
router.get('/:userName', (req, res, next) => {
res.render('index', {title: req.params.userName || "World"});
});

Question : Example of query Param and path Variable
Answer : 
router.get('/:userName', (req, res, next) => {
res.render('index', {title: req.params.userName || "World", lastName:req.query.lastName}
);
});
Example URL : http://localhost:3000/vikash?lastName=Mishra

Question : How to respond with the JSON?
Answer : We can use res.json to send the JSON respo
router.post('/', (req, res, next) => {
res.json({message : "POST Response"});
});

Question : How to accept a JSON request and response it with the JSON Object?
Answer :
router.post('/', (req, res, next) => {
res.json({message : req.body.message});
});

Question : explain the The 100 range
Answer : There are only two official status codes in the 100 range: 100 (Continue) and 101 (Switching Protocols). You’ll likely never deal with these yourself. If you do, check the specification or the list on Wikipedia.
Look at that! You are already one-fifth of the way through the status codes.

Question : Explain The 200 range
Answer : Steve Losh summarized the 200 range as “here you go.” The HTTP spec defines several status codes in the 200 range, but four of them are by far the most common.

200: OK
200 is the most common HTTP status code on the web by a long shot. HTTP calls status code 200 OK, and that’s pretty much what it means: everything about this request and response went through just fine. Generally, if you’re sending the whole response just fine and there aren’t any errors or redirects (which you’ll see in the 300s section), then you’ll send a 200 code.

201: Created
Code 201 is very similar to 200, but it’s for a slightly different use case. It’s common for a request to create a resource (usually with a POST or a PUT request). This might be creating a blog post, sending a message, or uploading a photo. If the creation succeeds and everything’s fine, you’ll want to send a 201 code. This is a bit nuanced, but it’s typically the correct status code for the situation.

202: Accepted
Just as 201 is a variant of 200, 202 is a variant of 201.

I hope I’ve beaten it into your head by now: asynchronousity is a big part of Node and Express. Sometimes you’ll asynchronously queue a resource for creation but it won’t be created yet.

If you’re pretty sure that the request wants to create a valid resource (perhaps you’ve checked that the data is valid) but you haven’t created it yet, you can send a 202 status code. It effectively tells the client, Hey, you’re all good, but I haven’t made the resource yet.

Sometimes you’ll want to send 201 codes and other times you’ll want to send 202; it depends on the situation.

204: No Content
204 is the delete version of 201. When you create a resource, you typically send a 201 or a 202 message. When you delete something, you often don’t have anything to respond with other than Yeah, this was deleted. That’s when you typically send a 204 code. There are a few other times when you don’t need to send any kind of response back, but deletion is the most common use case.

Exaplain the The 300 range
Answer : There are several status codes in the 300 range, but you’ll really only set three of them, and they all involve redirects.

301: Moved Permanently
HTTP status code 301 means Don’t visit this URL anymore; see another URL. 301 responses are accompanied with an HTTP header called Location, so you know where to go next.

You’ve probably been browsing the web and have been redirected—this probably happened because of a 301 code. This usually occurs because the page has moved.

303: See Other
HTTP status code 303 is also a redirect, but it’s a bit different. Just like code 200 is for regular requests and 201 is for requests where a resource is created, 301 is for regular requests and 303 is for requests where a resource is created and you want to redirect to a new page.

307: Temporary Redirect
There’s one last redirect status code: 307. Like the 301 code, you’ve probably been browsing the web and been redirected because of a 307 code. They’re similar, but they have an important distinction. 301 signals Don’t visit this URL ever again; see another URL; 307 signals See another URL just for now. This might be used for temporary maintenance on a URL.

Question : Explain The 400 range
Answer : The 400 range is the largest, and it generally means that something about the request was bad. In other words, the client made a mistake and it’s not the server’s fault. There are a lot of different errors here.

401 and 403: unauthorized and forbidden errors
There are two different errors for failed client authentication: 401 (Unauthorized) and 403 (Forbidden). The words unauthorized and forbidden sound pretty similar—what’s the difference?

In short, a 401 error occurs when the user isn’t logged in. A 403 error occurs when the user is logged in as a valid user, but they don’t have permissions to do what they’re trying to do.

Imagine a website where you couldn’t see any of it unless you logged in. This website also has an administrator panel, but not all users can administer the site. Until you logged in, you’ll see 401 errors. Once you logged in, you’ll stop seeing 401 errors. If you tried to visit the administrator panel as a non-admin user, you’d see 403 errors.

Send these response codes when the user isn’t authorized to do whatever they’re doing.

404: Not Found
I don’t think I have to tell you much about 404—you’ve probably run into it when browsing the web. One thing I found a little surprising about 404 errors is that you can visit a valid route but still get a 404 error.

For example, let’s say you want to visit a user’s page. The homepage for User #123 is at /users/123. But if you mistype and visit /users/1234 and no user exists with ID 1234, you’ll get a 404 error.

Other errors

There are a lot of other client errors you can run into—far too many to enumerate here. Visit the list of status codes at https://en.wikipedia.org/wiki/List_of_HTTP_status_codes to find the right status code for you.

When in doubt about which client error code to use, send a 400 Bad Request error. It’s a generic response to any kind of bad request. Typically, it means that the request has malformed input—a missing parameter, for example. Although there might be a status code that better describes the client error, 400 will do the trick.

Question : Explain The 500 range
Answer : The final range in the HTTP specification is the 500 range, and although there are several errors in this range, the most important one is 500: Internal Server Error. Unlike 400 errors, which are the client’s fault, 500 errors are the server’s fault. They can be for any number of reasons, from an exception to a broken connection to a database error.

Ideally, you should never be able to cause a 500 error from the client—that would mean that your client could cause bugs in your server.

If you catch an error and it really does seem to be your fault, then you can respond with a 500 error. Unlike the rest of the status codes where you want to be as descriptive as possible, it’s often better to be vague and say “Internal Server Error”; that way hackers can’t know where the weaknesses in your system lie. We’ll talk much more about this in chapter 10 when we talk about security.

Question : List down all the properties of req?
Answer : req.app :-
This property holds a reference to the instance of the Express application that is using the middleware.

If you follow the pattern in which you create a module that just exports a middleware function and require() it in your main file, then the middleware can access the Express instance via req.app

For example:
//index.js
app.get('/viewdirectory', require('./mymiddleware.js'))//mymiddleware.js
module.exports = function (req, res) {
    res.
send('The views directory is ' + req.app.get('views'));
});


req.baseUrl :
The URL path on which a router instance was mounted.
The req.baseUrl property is similar to the mountpath property of the app object, except app.mountpath returns the matched path pattern(s).

req.body :
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

req.hostname :
Contains the hostname derived from the Host HTTP header.
When the trust proxy setting does not evaluate to false, this property will instead have the value of the X-Forwarded-Host header field. This header can be set by the client or by the proxy.

req.ip :
Contains the remote IP address of the request.
When the trust proxy setting does not evaluate to false, the value of this property is derived from the left-most entry in the X-Forwarded-For header. This header can be set by the client or by the proxy.

req.params :
This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.

req.query :
This property is an object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.

req.route :
Contains the currently-matched route, a string.















Comments

Popular posts from this blog

NodeJS

Question : Why You should use Node JS? Answer :  Following are the major factor influencing the use of the NodeJS Popularity : The popularity can be important factor, as it has more user base and hence solution  of any common problem faced by developer can found easily online, without any professional help. JavaScript at all levels of the stack :  A common language for frontend and backend offers several potential benefits: The same programming staff can work on both ends of the wire Code can be migrated between server and client more easily Common data formats (JSON) exist between server and client Common software tools exist for server and client Common testing or quality reporting tools for server and client When writing web applications, view templates can be used on both sides Leveraging Google's investment in V8 Engine. Leaner, asynchronous, event-driven model Microservice architecture Question : example of node JS code? Answer :  const fs = require('fs'); const uti

Kubernetes

What is Kubernetes? Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem.  The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines over 15 years of Google’s experience running production workloads at scale with best-of-breed ideas and practices from the community. Why you need Kubernetes and what it can do? Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn’t it be easier if this behavior was handled by a system? That’s how Kubernetes comes to the rescue! Kubernetes provides you with a framework to run distributed systems resi

Spring Interview Question - Version 3.5

Spring Overview Question :   What is Spring? Answer : Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO based programming model.   Question : What are benefits of Spring Framework? Answer :   Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.   Inversion of control (IOC) : Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.   Aspect oriented (AOP) : Spring supports Aspect oriented programming and separates application business logic from system services.   C