Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

UNIT IV - EXPRESS AND ANGULAR

EXPRESS: Implementing Express in Node.js - Configuring routes - Using Request and Response objects.
Angular: Typescript - Angular Components - Expressions - Data binding - Built-in directives.

Implementing Express in Node.js

 Configuring Express Settings


 Starting the Express Server

Configuring Routes

 Implementing Routes
 Applying Parameters in Routes

Using Requests Objects & Response Objects

• Setting Headers
• Setting the Status
• Sending Response
• Sending JSON Responses
• Sending Files
• Sending a Download Response
• Redirecting the Response
EXPRESS JS: Fast, unopinionated, minimalist web framework for Node.js

 Express is a lightweight module that wraps the functionality of the Node.js http module in a simple-to- use interface
 Express is a node js web application framework that provides features for building web and mobile apps.
 It is used to build a single page, multipage, and hybrid web application.
 It is a layer built on the top of the Node js that helps manage servers and routes.

Version:

 Express 4.18.1
 Express 5.0 beta

Popular Node.js frameworks are built on Express:

 Express Gateway: Fully-featured and extensible API Gateway


 Blueprint: a SOLID framework for building APIs and backend services
 Kites: Template-based Web Application Framework
 Sails: MVC framework for Node.js for building production-ready apps.

Features of Express JS | Why Express JS? | Advantages:

 Minimalism & Flexibility - minimal & flexible Node.js web application framework for web & mobile app
 Robust Routing System - allows you to easily map URLs to specific functions or controllers
 Middleware Support - request handler that has access to the application's request-response cycle.
 Template Engine Integration – build dynamic content to make the application more organized &
maintainable.

Companies Using Express JS : Netflix, IBM, ebay, Uber

2 Marks

Command to install Express or npm install express


command to add the express module from the root of your project

setting up a port configuration const PORT = 3000 (or)

const PORT = process.env.PORT || 3000;

import the express module and create an instance of express or var express = require('express');
var app = express()
Starting the Express Server
app.listen(8080);
Configuring Express Settings app.enable('trust proxy');
app.disable('strict routing');
app.set('view engine', 'pug');
1. Implementing Express in Node.js
U plz write this in Paragraph | For understanding it’s in tabular form

Steps Description Coding

Create a new directory for the project and mkdir express-example


example
navigate into it: example
cd express-example
1. Set Up the
Project Initialize your project with npm init and
follow the prompts to create a npm init
package.json file.

2. Install
Install Express using npm: npm install express
Express
Create a file (e.g., app.js)
app.js and implement // File Name: app.js
the following Express application:

Import the Express module. const express = require('express');

Create an instance of the Express application const app = express();


using express(). const PORT = 3000;;
3. Create a
Express app.get('/', (req, res)) => {
Application Define a route for the root path ('/') that sends a
('Hello world
res.send('Hello world!');
response of "Hello, Express!" when accessed.
});

Set up the server to listen on port 3000.


3000
app.listen(PORT,, () => {
console.log(`Server is running on port ${PORT}`);
});

Save the changes and run the


4. Run the
application using the following
Application node app.js
command

Output Screen
Coding Without Explanation
2. Configuring Routes in Express JS
 Routing in Express JS is the process of specifying how an application replies to a client request to a
specific endpoint or URL.
 To run a function upon request for a certain route, route handlers are used.
 Syntax : app.method(path, [callback . . .], callback)
 Two parts are there in defining routes:
1. HTTP Request Method:
 The HTTP request method determines the type of operation the client is requesting.
 Different HTTP request methods are used for different purposes:
 GET : retrieving data from the server.
 POST : submitting data to be processed to a specified resource.
 PUT : updating a resource on the server.
 DELETE : requesting that a resource be removed or deleted.

2. Path Specified in the URL:


 The path in the URL specifies the endpoint or route on the server that the client is trying to access.
 For example:
/ : represents the root of the website.
/login : represents the login page.
/cart : represents a shopping cart page.
 There are four main methods for implementing parameters in a route:
Query string, POST params , regex. Defined parameter:
 Example :
const express = require('express'); // Import required modules
const app = express(); // Create an Express application
const port = 3000;
app.get('/', function(req, res) // Defining Routes – Server Root
{
res.send("Server Root");
});
app.get('/login', function(req, res) //Defining Routes – Login Page
{
res.send("Login Page");
});
app.get('/find', function(req, res) //Defining Routes – Find Page
{ // Applying parameters to route
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Student: Name: ' + query.name + ' Branch: ' + query.branch);
});
For example, consider the following URL: find?name = Arun & branch = IT
The res.send() method returns: Finding Student: Name : Arun Branch : IT
3. Using Request and Response objects in Express JS
 In an Express.js application, the request (req) and response (res) objects are fundamental to handling
HTTP requests and sending responses.
 Request Object (req):
 The req object represents the HTTP request and contains information about the data and
metadata of the request made by the client.
 It provides access to parameters, URL,query strings, headers, and the request body.

Example :

}); Output
Response Object(res)
 The res object represents the HTTP response that an Express app sends when it receives an HTTP request.
 It provides methods for sending a response, setting headers, and managing the response body.
Description Method Definition

get(header) Returns the value of the header specified.


Setting Headers
set(header, value) Sets the value of the header.

setHeader(name, value) Sets a single header value for the response.

send([body]) Sends the HTTP response.


Sending
Response & File
sendFile(path) Sends a file as an octet stream.

json([body]) Sends a JSON response


Sending JSON
Responses Sends JSON data without worrying about cross-
jsonp([object])
domain issues
Sending
Download download(path, [filenme], [calback]) Sends the file in the HTTP response as an attachment
Response
Redirecting the
redirect(path) Handles redirection of the request to a new location
Response
Setting the Status status(code) Sets the HTTP response status code.

End the response end() Ends the response process.


Example :
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.set('Content-Type', 'text/plain'); // 1. Setting and Getting Headers
const contentType = res.get('Content-Type');
console.log('Content-Type:', contentType);
res.setHeader('Cache-Control', 'no-store'); // 2. Alternative method for setting headers
res.send('Hello, this is a simple response!'); // 3. Sending a basic response
res.sendFile(__dirname + '/example.txt'); // 4. Sending a file
const jsonData = { message: 'This is a JSON response.' }; // 5. Sending JSON response
res.json(jsonData);
res.jsonp({ message: 'This is a JSONP response.' });
res.download(__dirname + '/example.txt', 'custom_filename.txt'); // 6. Downloading a file
res.redirect('../new-path'); // 7. Redirecting to another path
res.status(400); // 8. Setting HTTP status code
res.end(); // 9. Ending the response
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
2 marks :

How do you set the HTTP status for the response and list the different statuses?
To set the status response, use the status(number) method where the number parameter is the HTTP response status
Example :
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

-----------------

You might also like