0% found this document useful (0 votes)
26 views10 pages

IV

Uploaded by

ANISHYA P IT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views10 pages

IV

Uploaded by

ANISHYA P IT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

UNIT -IV

Implementing Express in Node.js – Configuring routes – Using Request and Response


objects–Angular – Typescript - Implementing Classes, Modules, Functions – Angular
Components.

What is Express?
Express is a 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 middle ware and routing; it adds helpful
utilities to Node.js’s HTTP objects;it facilitates the rendering of dynamic HTTP objects.
Express is a part of MEAN stack, a full stack JavaScript solution used in building fast, robust, and
maintainable production web applications.
• MongoDB(Database)
• ExpressJS(Web Framework)
• AngularJS(Front-end Framework)
• NodeJS(Application Server)

4.1 Implementing Express in Node.js.

• Express is a lightweight module that wraps the functionality of the Node.js http module.
• Express also extends the functionality to handle server routes, responses, cookies, and statuses of
HTTP requests.
Steps included in implementing express
• Installing express
• Configuring setting
• Starting the express server
Getting Started with Express
• Add the express module using the following command from the root of your project:
npm install express
• Also add express to your package.json module to ensure that express is installed when you deploy
your application.
• Once you have installed express, you need to create an instance of the express class to act as the
HTTP server for your Node.js application.
• The following lines of code import the express module and create an instance of express that you
can use:
var express = require('express’);
var app = express();
Configuring Express Settings
Express provides several application settings that control the behavior of the Express server.
The express object provides the set(setting, value) and enable(setting) and disable(setting)
methods to set the value of the application settings.
To get the value of a setting, you can use the get(setting), enabled(setting), and disabled(setting) methods.
For example:
app.enabled('trust proxy'); \\true
app.disabled('strict routing'); \\true
app.get('view engine'); \\pug
Starting the Express Server

• To begin implementing Express as the HTTP server for your Node.js application, you need to
create an instance and begin listening on a port.
var express = require('express’);
var app = express();
app.listen(8080);
• The app.listen(port) call binds the HTTP connection to the port and begins listening on it.
• In fact, the value returned by express() is actually a callback function that maps to the callback
function that is passed into the http.createServer() and https.createServer() methods.
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
host: '127.0.0.1’,
key: fs.readFileSync('ssl/server.key’),
cert: fs.readFileSync('ssl/server.crt')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.get('/', function(req, res){
res.send('Hello from Express');
});

4.2 Configuring Routes


• A route describes how to handle the path portion of the URI in the HTTP request to the Express
server.
Implementing Routes
• There are two parts when defining the route.
• First is the HTTP request method (typically GET or POST). Each of these methods often needs
to be handled completely differently.
• Second, is the path specified in the URL—for example, / for the root of the website, /login for
the login page, and /cart to display a shopping cart.
The express module provides a series of functions that allow you to implement routes for the Express
server. These functions all use the following syntax:
app.<method>(path, [callback . . .], callback)
The <method> portion of the syntax actually refers to the HTTP request method, such as GET or POST.
For example:
app.get(path, [middleware, ...], callback)
app.post(path, [middleware, ...], callback)
The path refers to the path portion of the URL that you want to be handled by the callback function.
The middleware parameters are 0 or more middleware functions that are applied before executing the
callback function.
The callback function is the request handler that handles the request and sends the response back to the
client.
The callback function accepts a Request object as the first parameter and a Response object as the
second.
app.get('/', function(req, res){
res.send("Server Root");
});
app.get('/login', function(req, res){
res.send("Login Page");
});
app.post('/save', function(req, res){
res.send("Save Page");
});
When the Express server receives an HTTP request, it looks for a route that has been defined for the
appropriate HTTP method and path. If one is found, a Request and Response object is created to manage
the request and is passed into the callback function(s) for the route.
app.all('*', function(req, res){
// global handler for all paths
});
app.all('/user/*', function(req, res){
// global handler for /user path
});
Applying Parameters in Routes
• To reduce the number of routes, you can implement parameters within the URL.
• Parameters allow you to use the same route for similar requests.
• For example, you would never have a separate route for every user or product in your system.
• Instead you would pass in a user ID or product ID as a parameter to one route, and the server code
would use that ID to determine which user or product to use.
• There are four main methods for implementing parameters in a route:
Query string: Uses the standard ?key=value&key=value... HTTP query
string after the path in the URL.
POST params: When implementing a web form or other POST request, you can pass parameters in the
body of the request.
regex: Defines a regular expression as the path portion of the route.
Defined parameter: Defines a parameter by name using :<param_name> in the path portion of the route.
Express automatically assigns that parameter a name when parsing the path.
Applying Route Parameters Using Query Strings
• The simplest method to add parameters to a route is to pass them using the normal HTTP query
string format of ?key=value&key=value...
• Then you can use the url.parse() method is to parse the url attribute of the Request object to get
the parameters.
• The following code implements a basic GET route to /find?author=
<author>&title=<title> that accepts author and title parameters. To
actually get the value of author and title, the url.parse() method is used to build a query object:
app.get('/find', function(req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Book: Author: ' + query.author + ' Title: ' + query.title);
});
For example, consider the following URL:
/find?author=Brad&title=Node
The res.send() method returns:
Finding Book: Author: Brad Title: Node
Applying Route Parameters Using Regex
• One way to implement parameters in routes is to use a regex expression to match patterns.
• This allows you to implement patterns that do not follow a standard / formatting for the path.
• The following code implements a regex parser to generate route parameters for GET requests at
the URL /book/<chapter>:<page> path.
• Notice that the values of the parameters are not named; instead, req.params is an array of
matching items in the URL path.
• app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res){
• res.send('Get Book: Chapter: ' + req.params[0] +
• ' Page: ' + req.params[1]);
• });
• For example, consider the following URL:
• /book/12:15
• The res.send() method returns
• Get Book: Chapter: 12 Page: 15
Applying Route Parameters Using Defined Parameters
• If your data is more structured, a defined parameter is a better method to use than regex.
• You define parameters in the path of the route using : <param_name>.
• When using defined parameters, req.param is a function instead of an array, where calling
req.param(param_name) returns the value of the parameter.
• The following code implements a basic :userid parameter expecting a URL with
/user/ :userid
app.get('/user/:userid', function (req, res) {
res.send("Get User: " + req.param("userid"));
});
• For example, consider the following URL:
/user/4983
The res.send() method returns
Get User: 4983
Applying Callback Functions for Defined Parameters
• A major advantage of using defined parameters is that you can specify callback functions that
are executed if the defined parameter is found in a URL.
• When parsing the URL, if Express finds a parameter that has a callback registered, it calls the
parameter’s callback function before calling the route handler.
• To register a callback function, you use the app.param() method.
• The app.param() method accepts the defined parameter as the first argument, and then a callback
function that receives the Request, Response, next, and value parameters.
app.param(param, function(req, res, next, value){} );
• The Request and Response objects are the same as are passed to the route callback.
• The next() calls the next registered callback. It is called not to break the callback chain.
• The value parameter is the value of the parameter parsed from the URL path.
• For example,
app.param('userid', function(req, res, next, value){
console.log("Request with userid: " + value);
next();
});
To see how the preceding code works, consider the following URL: /user/4983
The userid of 4983 is parsed from the URL and the consol.log() statement displays Request with userid:
4983

4.3 Using Request and Response objects

Using Requests Objects


• The route handlers are passed a Request object as the first parameter.
• The Request object provides the data and metadata about the request, including the URL, headers,
query string, and much more.
• This allows you to handle the request appropriately in your code.
express_request.js: Accessing properties of the Request object in Express
var express = require('express');
var app = express();
app.listen(80);
app.get('/user/:userid', function (req, res) {
console.log("URL:\t " + req.originalUrl);
console.log("Protocol: " + req.protocol);
console.log("IP:\t " + req.ip);
console.log("Path:\t " + req.path);
console.log("Host:\t " + req.host);
res.send("User Request");
});
Using Response Objects
The Response object passed to the route handler provides the necessary
functionality to build and send a proper HTTP response.
• Setting Headers
An important part of formulating a proper HTTP response is to set the headers. For example, setting the
Content-Type header determines how the browser handles the response.
For example, the following code first gets the Content-Type header and then sets it:
var oldType = res.get('Content-Type’);
res.set('Content-Type', 'text/plain');
Setting the Status
You also need to set the HTTP status for the response if it is something other than 200.
It is important to send the correct status response so that the browser or other applications can handle the
HTTP response correctly.
To set the status response, use the status(number) method where the number parameter is the HTTP
response status defined in the HTTP spec.
For example, the following lines set different statuses:
res.status(200); // OK
res.status(300); // Redirection
res.status(400); // Bad Request
res.status(401); // Unauthorized
res.status(403); // Forbidden
res.status(500); // Server Error
Sending Response
• The send() method can use one of the following formats, where status is the HTTP status code and
body is a String or Buffer object:
res.send(status, [body])
res.send([body])
• If you specify a Buffer object, the Content-Type is automatically set to application/octet-stream
unless you explicitly set it to something else.
• For example:
res.set('Content-Type', 'text/html’);
res.send(new Buffer('<html><body>HTML String</body></html>'));
• The send() method can really handle all the responses necessary as long as you set the appropriate
headers and status for the response.
• Once the send() method completes, it sets the value of the res.finished and res.headerSent
properties.
• You can use these to verify the response was sent as well as how much data was transferred. The
following shows an example value of the res.headerSent property:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html
Content-Length: 92
Date: Tue, 17 Dec 2013 18:52:23 GMT
Connection: keep-alive
Sending JSON Responses
Express facilitates sending JSON by providing the json() and jsonp() methods on the Response object.
These methods use a similar syntax as send() except that the body is a JSON stringifiable JavaScript
object:
res.json(status, [body])
res.json([body])
res.jsonp(status, [body])
res.jsonp ([body])
Sending Files
A great helper method in Express is the sendfile(filepath) method on the Response object.
The sendfile() method does everything that needs to be done to send files to the client in a single function
call.
Specifically, the sendfile() method does the following:
Sets the Content-Type header to the type based on file extension Sets other appropriate headers such as
Content-Length
Sets the status of the response
Sends the contents of the file to the client using the connection inside the Response object
The sendfile() method uses the following syntax:
res.sendfile(path, [options], [callback])
Sending a Download
Response Express also includes a res.download() method that works similarly to the res.sendfile() method
with only a few differences.
The res.download() method sends the file in the HTTP response as an attachment.
The res.download() method uses the following syntax:
res.download(path, [filename], [callback])
Redirecting the Response
A common need when implementing a webserver is the ability to redirect a request from the client to a
different location on the same server or on a completely different server.
The res.redirect(path) method handles redirection of the request to a new location.

4.4 Typescript
TypeScript is a superset of JavaScript that adds static typing, interfaces, and advanced features to
the language. In Angular applications, TypeScript enhances code quality and maintainability by providing
strong typing, improved tooling, better error detection during development, and support for object-
oriented programming concepts, leading to more robust and scalable applications.
A TypeScript class is defined using the class keyword, followed by the class name and a body
containing properties and methods. For example:
class Car {
constructor(public brand: string, public model: string) {}
drive() {
console.log(`Driving a ${this.brand} ${this.model}`);
}
}

4.5 Interfaces in Typescript

An interface in TypeScript defines the structure of an object, specifying what properties and
methods it should have. Interfaces are useful for type-checking and ensuring that classes or objects adhere
to a specific contract.
Example of an Interface
interface Vehicle {
brand: string; // Property
model: string; // Property
year: number; // Property
displayInfo(): string; // Method
}

// Implementing the interface in a class


class Car implements Vehicle {
constructor(
public brand: string,
public model: string,
public year: number
) {}

displayInfo(): string {
return `${this.brand} ${this.model}, Year: ${this.year}`;
}
}

const myCar = new Car('Toyota', 'Camry', 2021);


console.log(myCar.displayInfo()); // Output: Toyota Camry, Year: 2021

4.6 Implementing Modules and functions in TypeScript

Introduction to Modules in TypeScript


Modules in TypeScript are a way to organize code into reusable blocks. They allow you to encapsulate
functionality and expose only what is necessary to other parts of your application. Modules help prevent
naming collisions and enable code to be organized in a more structured manner.
Creating and Using Modules
1. Defining a Module: A module is simply a TypeScript file (with the .ts extension) that contains
code related to a specific functionality. You can define modules using export and import
statements.
2. Example of a Simple Module:
Let's create a module named mathUtils.ts that contains functions for basic mathematical operations.
// mathUtils.ts
// Exporting functions
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
export function multiply(a: number, b: number): number {
return a * b;
}
export function divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
3. Importing and Using the Module:
To use the functions defined in mathUtils.ts, you need to import them into another TypeScript file, for
example, app.ts.
// app.ts
import { add, subtract, multiply, divide } from './mathUtils';
const a: number = 10;
const b: number = 5;
console.log(`Addition: ${add(a, b)}`); // Output: Addition: 15
console.log(`Subtraction: ${subtract(a, b)}`); // Output: Subtraction: 5
console.log(`Multiplication: ${multiply(a, b)}`); // Output: Multiplication: 50
console.log(`Division: ${divide(a, b)}`); // Output: Division: 2
Implementing Functions in TypeScript
Functions in TypeScript can have types, which help to ensure that the inputs and outputs are of expected
types. Functions can be defined in several ways:
1. Basic Function Declaration:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
2. Anonymous Functions:
Anonymous functions can be assigned to variables.
const square = function (x: number): number {
return x * x;
};
console.log(square(4)); // Output: 16
3. Arrow Functions:
Arrow functions provide a shorter syntax.
const cube = (x: number): number => {
return x * x * x;
};

console.log(cube(3)); // Output: 27
4. Function Overloading:
TypeScript allows function overloading, where you can define multiple signatures for a single function.
function multiply(x: number, y: number): number;
function multiply(x: string, y: string): string;
function multiply(x: any, y: any): any {
return x * y;
}

console.log(multiply(2, 3)); // Output: 6


console.log(multiply("Hello, ", 3)); // Output: Hello, Hello, Hello,

You might also like