Express JS

 

Mention the arguments that are available in an Express JS route handler function.

The arguments that are available in the route handler function of Express JS are given below:

  • Res - It is the response object.
  • Req - It is the request object
  • Next (optional) - This argument is used for passing the management to any of the above-given route handlers.
Express passes a next callback to every route handler and middleware function that can be used to break logic for single routes across multiple handlers. Calling next() with no arguments tells express to continue to the next matching middleware or route handler. Calling next(err) with an error will trigger any error handler middleware. Calling next('route') will bypass any subsequent middleware on the current route and jump to the next matching route. This allows domain logic to be decoupled into reusable components that are self-contained, simpler to test, and easier to maintain and change.

Serving static files in Express

The app.use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path.

app.use([path], callback, [callback])

Parameters

  • path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.

  • callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).


The express.json() function is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express

1. Routing

In Express JS, Routing determines an application's response to the client's request to a specific endpoint, a URI (or path), and a specific HTTP request method.

Each route contains one or more handler functions and is executed when the route is matched.

Following is the structure of Routing:

app.METHOD(PATH, HANDLER)

Where:

  • The app is an express's instance.
  • METHOD is an HTTP request method
  • PATH is a server's path
  • HANDLER is a callback function executed when the matching route is found.

You can use four HTTP methods within the request. These methods help in identifying the function made by the user. Let's learn about each HTTP method in detail:

  • GET: The HTTP GET method helps retrieve information from the server using a given URI. The GET requests only retrieve data without causing any other effect on the data.
  • POST: The HTTP POST request method sends data to a server or updates a resource.
  • PUT: The HTTP PUT request method helps accept the data enclosed within the request as an alteration to the current object specified by the URL.
  • DELETE: This method requests the server to delete a particular resource from the destination.

The following example illustrates the usage of all HTTP methods:

var express = require('express');
const app = express();
app.use(ExpressJSon());

app.get('/', (req, res) => {
  res.send('Hello World!')
})
app.post('/', (req, res) => {
  res.send('Got a POST request')
})
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
})
app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user')
})






What is an API?

When you’re using scrolling through Instagram on your phone, the app sends some requests to its server. Their server receives the request, processes it, and returns a response to your phone. The app on your phone processes the response and presents it to you in a readable manner. Here, the app on your phone talks to Instagram’s servers via what we call Application Programming Interface or APIs.

Let’s take another example to understand APIs. You must have heard of UPI payments and apps like GPay, PhonePe, and Paytm which allow you to do transactions via UPI. The UPI payment system is managed by NPCI or National Payments Corporation of India which exposes its APIs so that these payment apps can use them and facilitate UPI transactions to their customers. Simply put, an API is a way for two or more software systems to communicate with each other.

The application sending the request is commonly referred to as a client and the application sending the response is called the server. So, in the above example, the app on your device is the client which requests data from Instagram’s servers.

The way an API works is that the client sends some request to the server at a particular endpoint, with some payload using one of the HTTP methods; the server processes the request and returns a response which can be in HTML, XML, JSON, etc.

What is the MVC?

MVC stands for Model, View, Controller is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each one of these components is built to handle specific development aspects of an application.

MVC is architecture used in building Web Servers that focus on reliability and making the development process much simpler and easier since it composes the Web Server into three separate parts.

  • Controller is the part that takes care of client request processing which handles the HTTP Request and returns a response the response could be either a JSON if you’re calling an API endpoint or regular HTML webpage.
  • Model is the database interface which lets you interact with the database API and create different entity schemas of your app on the database (MySQL, MongoDB), it gets called from controller depending on the client’s request if it needs a stored data then the controller will ask the model interface for providing it with the needed data.
  • View is what compiles and renders into plain HTML and what the client in most cases going to get back as a response of what he requested (for ex: to view his profile details), the view needs to use a Template Engine for doing the rendering process where the controller feed it with needed data (data from database and client) and the view renders and convert everything into plain HTML that the browser could understand and display.

What is CORS?

CORS is a technique that permits resource sharing between scripts running on a browser client and resources from a different origin. Cross-Origin Resources Sharing uses additional HTTP headers to instruct the browser to allow a web application running at one domain to access specific resources from a server at a different origin. A few years ago, AJAX requests and web fonts resource sharing were restricted by the same-origin policy. However, today, developers can use CORS to facilitate cross-domain communication from the browser. The CORS protocol supports cross-origin data transfers and requests between web servers and browsers. CORS determines whether origin requests are made or not. And before we go further, let’s look at the two different request types.

 Differentiate between worker threads and clusters in Node JS.

Cluster:

  • Each CPU has one process with an IPC to communicate.
  • Clusters help when multiple servers are required to accept HTTP requests through a single port.
  • The processes have separate memory because of being spanned in different CPUs leading to memory issues.

Clusters in Node JS

Worker Threads:

  • Only a single process is there with multiple threads.
  • Each Node contains one Node having most APIs accessible.
  • The memory is shared with other threads.
  • We can use this for CPU-intensive tasks.

Differentiate between Node JS and Express JS.

Node JS is an open-source platform on which the JavaScript code is executed outside of a browser. It is used by several companies, including Uber, Walmart, Netflix, etc. It is a platform acting as a web server and not a programming language or framework. On the other hand, Express JS is a framework built on Node JS.

What is bcryptjs?



Bcryptjs is a library that can be used to hash passwords before storing and also comparing plain text passwords with hashed passwords to see if they match.

bcrypt's hash() function is how to create a secure hash of a password. It takes two parameters: the password and the number of salt rounds. Increasing the number of salt rounds makes bcrypt.hash() slower, which makes your passwords harder to brute force.

const bcryptjs = require('bcryptjs');

const numSaltRounds = 8;

const password = 'password';

bcryptjs.hash(password, numSaltRounds);

We generally recommend a higher numSaltRounds in production (at least 8). However, we often use numSaltRounds = 1 in tests to make tests run faster.

The bcrypt-js library also has a bcryptjs.hashSync(password, numSaltRounds) function. We recomment not using hashSync(), because hashSync() will block your entire Node process while it runs.

compare()

The compare() function is used to essentially decrypt the password. It takes two parameters: the password and the hash. If the function returns true, then the password passed was the correct password.

const bcryptjs = require('bcryptjs');

const numSaltRounds = process.env.NODE_ENV === 'test' ? 1 : 12;

const password = 'password';

const hash = bcryptjs.hash(password, numSaltRounds);

bcryptjs.compare(password, hash); // true

There is no way to get the original password from the bcrypt hash without guessing the password.

Make sure you use the exact same number of salt rounds when generating the hash using hash(), and when comparing using compare(). If you compare() using a different number of salt rounds than the hash was generated with, compare() will always fail.

https://dev.to/victuk/hashing-and-comparing-hashed-passwords-with-bcryptjs-synchronous-method-56h2

Hashing a password

"Hashing" a password refers to taking a plain text password and putting it through a hash algorithm. The hash algorithm takes in a string of any size and outputs a fixed-length string. No matter the size of the original string (i.e., the plain text password), the output (the hash) is always the same length. Since the same process is always applied, the same input always yields the same output.

Say the plain text password is Ralph$467. Every time you pass Ralph$467 into the hash algorithm, the returned hash is the same. If someone else's plain text password is jsu*^7skdl230H98, the length of its hash is the same as for Ralph$467.

Because hash algorithms always produce the same result for a specific password, they are predictable. If you only hash the password, a hacker can figure out the original password. Hashing is not enough.

Salting a password

salt is a random string. By hashing a plain text password plus a salt, the hash algorithm’s output is no longer predictable. The same password will no longer yield the same hash. The salt gets automatically included with the hash, so you do not need to store it in a database.

Introduction

Your passwords are not stored as plain text on any website you've signed up for. The reason for this is that if someone gets access to the database, they will find it difficult to know the passwords of any account they have seen on the database.

Hashing is the process of converting plain text into another value. The hash generated can be compared with the plain text, but, when plain text is hashed it can't be converted back to plain text. Also, a good hashing algorithm is supposed to generate unique hashes even if the same plain is hashed. This means if I hash a word like "comfortable" twice, for example, it should generate unique values each time I hash it.

What is bcryptjs?

Bcryptjs is a library that can be used to hash passwords before storing and also comparing plain text passwords with hashed passwords to see if they match.

Setup bcryptjs

Create a folder, name it "bcrypt-tutorial", inside the folder, open a terminal and type "npm init -y" to create a project, then type "touch index.js" to create an index.js file to be used to write our code.
After this, you open "bcrypt-tutorial" with your favorite code editor, in this article I'll use VS Code.

Then, you install bcryptjs by using the command

npm install bcryptjs

So far, you've created a folder for the project, created a project so that your dependencies can be managed from within the folder and you've installed "bcryptjs", well done.

How to hash a password

Let's say the password we want to hash is "comfortable".

Inside the index.js file you created after requiring/importing bcryptjs, type the following:

const bcrypt = require("bcryptjs");

const password = "comfortable";

const salt = bcrypt.genSaltSync(10);

const hashedPassword = bcrypt.hashSync(password, salt);

console.log(hashedPassword);

Let me explain the lines of code we have written so far:

const bcrypt = require("bcryptjs");

This line of code imports the bcryptjs package to be used inside the indes.js file.

const password = "comfortable";

The password we want to hash.

const salt = bcrypt.genSaltSync(10);

This is the salt generated to be used to hash the plain password. A hash salt can be defined as the cost factor for the hash function - incrementing it by one will double the time taken to calculate the hash. The "10" passed as an argument means the hash function will take 10 times the time to calculate the hash.

const hashedPassword = bcrypt.hashSync(password, salt);

This line of code actually hashes the password using the salt generated using "bcrypt.genSaltSynce()".

console.log(hashedPassword);

This line of code shows the result of hashing the password.

This is the result i got $2a$10$qADzCMgxKJjE7gLNdh0M6.cWWYyyDDHUCQWMAXdk87pFuOrkCSpQO

Up next, I guess you will want to know how to compare the hashed password with the plain password, let's see how to do that.

How to compare a plain password with a hashed password.

Let's say you want to compare the original password (which is "comfortable") with the hashed password to see if they match, here is how to do it.

const bcrypt = require("bcryptjs");

const password = "comfortable";

// The value of the he password I hashed
// Your's will be different
const hashedPassword = "$2a$10$qADzCMgxKJjE7gLNdh0M6.cWWYyyDDHUCQWMAXdk87pFuOrkCSpQO";

const passwordsMatch = bcrypt.compareSync(password, hashedPassword);

console.log(passwordsMatch);

if(passwordsMatch) {
    console.log("Passwords match");
} else {
    console.log("Passwords don't match");
}

Let me explain what we've written so far.

const hashedPassword = "...";

The value of the password that was hashed.

const passwordsMatch = bcrypt.compareSync(password, hashedPassword);

We use this line of code to compare the plain password with the hashed password to see if they match. This will return a Boolean of true if the passwords match and false if the passwords don't match.

if(passwordsMatch) {
console.log("Passwords match");
} else {
console.log("Passwords don't match");
}

This line of code takes the Boolean value stored as passwordsMatch and uses it to print a message to the user if the passwords match or not.

The result I got:

true
Passwords match

Conclusion

This method can be used when setting up a registration route on your server. Before saving any user's password, always make sure you hash it.

Comments