0% found this document useful (0 votes)
2 views31 pages

FS Module-4 (1)

The document outlines a course on Full Stack Development, focusing on the MERN stack and Express.js framework. It covers key concepts such as routing, middleware, REST APIs, and GraphQL, along with practical implementations and best practices. Resources for further learning, including textbooks and online lectures, are also provided.

Uploaded by

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

FS Module-4 (1)

The document outlines a course on Full Stack Development, focusing on the MERN stack and Express.js framework. It covers key concepts such as routing, middleware, REST APIs, and GraphQL, along with practical implementations and best practices. Resources for further learning, including textbooks and online lectures, are also provided.

Uploaded by

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

Full Stack Development

Manjunath G.S.
Asst. Professor,
Dept. of CS-ICB
Text Books
Web links and Video Lectures (e-Resources):
• https://github.com/vasansr/pro-mern-stack
• https://nptel.ac.in/courses/106106156
• https://archive.nptel.ac.in/courses/106/105/106105084/

• Activity Based Learning


• Course Project- Build Web applications using MERNstack.
Module-4 Syllabus
• Express: Routing, Request Matching, Route Parameters,
Route Lookup, Handler Function, Request Object,
Response Object, Middleware, REST API, Resource Based,
HTTP Methods as Actions, GraphQL, Field Specification,
Graph Based, Single Endpoint, Strongly Typed,
Introspection, Libraries, The About API GraphQL Schema
File, The List API, List API Integration, Custom Scalar
types, The Create API, Create API Integration, Query
Variables, Input Validations, Displaying Errors.
• Textbook 2: Chapter 5
Express
• Express.js is a minimal and flexible Node.js web application
framework that simplifies the development of server-side
applications.
• It provides a robust set of features to handle HTTP requests,
routing, middleware, and more.
• Express helps developers build fast, scalable, and maintainable
web applications and APIs with ease.
• Express was created to streamline the process of building web
applications with Node.js, by offering a simple interface.
Key Features
• Routing
• Middleware
• Template Engines: Express supports template engines like EJS,
Pug, and Handlebars to render dynamic HTML views.
• Easy Integration with Databases
• RESTful APIs: To handle CRUD operations.
• Error Handling
• Highly Configurable
Routing
• Routing in Express.js refers to how an application responds to
client requests (such as GET, POST, PUT, DELETE) to specific
endpoints (URLs).
• With Express, defining routes is very easy and flexible. Routes map
HTTP requests to specific functions, which is crucial for building
APIs and web pages.
Key Concepts of Routing
• Route Definition: A route defines the URL and HTTP method (e.g.,
GET, POST) that an application will listen for and respond to.
• Route Handlers: The functions that execute when a route is
matched. These functions can send back responses, interact with
databases, perform business logic, etc.
• Route Parameters: Dynamic placeholders in a URL that can
capture values, like user IDs or product names.
• Query Parameters: Parameters appended to the URL, typically
after a ?, that are used to pass data in a URL.
Basic Syntax of Route Definition
• To define a route in Express, we use app.METHOD() where
METHOD is the HTTP method (such as get, post, put, or delete),
and the first argument is the path.
• app.get('/home', (req, res) => {
• res.send('Welcome to the Home Page!');
• });
• app.get(): This defines a route that listens for GET requests.
• /home: The URL or path the route is associated with.
Request Matching
• When a request is received, the first thing that Express does is match
the request to one of the routes.
• The request method is matched against the route’s method.
• Further, the request URL is matched with the path specification, the
first argument in the route, which is /hello.
• When a HTTP request matches this specification, the handler function
is called.
• The route’s method and path need not be specific. If you want to match
all HTTP methods, you could write app.all().
• If you needed to match multiple paths, you could pass in an array of
paths, or even a regular expression like '/*.do' will match any request
ending with the extension .do
Route Parameters
• Route parameters are named segments in the path specification that
match a part of the URL.
• If a match occurs, the value in that part of the URL is supplied as a
variable in the request object.
• This is used in the following form:
app.get('/customers/:customerId', ...)
• The URL /customers/1234 will match the route specification, and so
will /customers/4567. In either case, the customer ID will be captured
and supplied to the handler function as part of the request in req.
params, with the name of the parameter as the key. Thus,
req.params.customerId will have the value 1234 or 4567 for each of
these URLs, respectively.
Route Lookup
• Multiple routes can be set up to match different URLs and
patterns.
• The router does not try to find a best match; instead, it tries to
match all routes in the order in which they are installed. The first
match is used.
• So, if two routes are possible matches to a request, it will use the
first defined one. So, the routes have to be defined in the order of
priority.
• Thus, if you add patterns rather than very specific paths, you
should be careful to add the more generic pattern after the specific
paths in case a request can match both.
Handler Function
• Once a route is matched, the handler function is called, which in
the previous example was an anonymous function supplied to the
route setup function.
• The parameters passed to the handler are a request object and a
response object.
• The handler function is not expected to return any value.
• But it can inspect the request object and send out a response as
part of the response object based on the request parameters.
Request Object
• Any aspect of the request can be inspected using the request
object’s properties and methods.
• A few important and useful properties and methods are listed
here:
• req.params
• req.query
• req.header, req.get(header)
• req.path
• req.url, req.originalURL
• req.body
Response Object
• The response object is used to construct and send a response.
• Note that if no response is sent, the client is left waiting.
• A few important and useful properties and methods are listed
here:
• res.send(body)
• res.status(code)
• res.json(object)
• res.sendFile(path)
Middleware
• Middleware functions are an essential concept that enables the
processing of requests and responses in the application pipeline.
• Middleware functions are functions that have access to the request
object (req), the response object (res), and the next middleware
function in the application's request-response cycle.
• Middleware functions are executed sequentially in the order they
are defined.
• Middleware can end the request-response cycle by sending a
response or call next() to pass control to the next middleware.
Middleware
Application-Level Middleware
• These are bound to an instance of the Express application using
app.use() or specific HTTP methods like app.get() or app.post().
Router-Level Middleware
• These work similarly to application-level middleware but are
specific to an instance of express.Router().
Error-Handling Middleware
• Error-handling middleware must have four arguments: (err, req,
res, next).
Application Level Middleware
const express = require('express');
const app = express();

app.use((req, res, next) => {


console.log('Request URL:', req.url);
next(); // Pass control to the next middleware
});

app.get('/', (req, res) => {


res.send('Hello World!');
});

app.listen(3000, () => console.log('Server running on port 3000'));


Router Level Middleware
const express = require('express');
const app = express();
const router = express.Router();

router.use((req, res, next) => {


console.log('Router-level middleware executed.');
next();
});

router.get('/', (req, res) => {


res.send('Router Middleware Example');
});

app.use('/router', router);

app.listen(3000, () => console.log('Server running on port 3000'));


Error-Handling Middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
REST API
• REST API (Representational State Transfer Application
Programming Interface) is a set of rules and conventions for
building and interacting with web services.
• REST is an architectural style that allows systems to communicate
using stateless, client-server protocols, primarily HTTP.
• REST APIs are widely used for creating scalable, maintainable, and
flexible web services.
REST API
REST API
Although the HTTP method and operation mapping are well mapped and
specified, REST by itself lays down no rules for the following:
• Filtering, sorting, and paginating a list of objects. The query string is
commonly used in an implementation-specific way to specify these.
• Specifying which fields to return in a READ operation.
• If there are embedded objects, specifying which of those to expand in a
READ operation.
• Specifying which fields to modify in a PATCH operation.
• Representation of objects. You are free to use JSON, XML, or any other
representation for the objects in both READ and WRITE operations.
GraphQL
• What is GraphQL?
• A query language for APIs.
• Runtime for executing those queries.
• Developed by Facebook in 2015.
• Focus on flexibility and efficiency.
• Key feature: Fetch only the data you need.
Benefits Over REST
Components of a Full-Stack GraphQL
Application
• Frontend: Query data via a GraphQL client (e.g., Apollo Client,
Relay).
• Backend: Serve data with a GraphQL API (e.g., Apollo Server,
GraphQL Yoga).
• Database: Store and manage data (e.g., MongoDB, PostgreSQL).
• Middleware: Handle authentication, authorization, and data
transformation.
Frontend Implementation
• Tools:
• Apollo Client: Simplifies state management and data fetching.
• Relay: Highly optimized for large-scale applications.
• Features:
• Query composition.
• Optimistic UI updates.
• Caching for performance.
• Code Example: Simple query example in JavaScript/React.
Backend Implementation
• Tools:
• Apollo Server: GraphQL server framework.
• Express.js for middleware integration.
• Features:
• Schema definition: Types, Queries, Mutations.
• Resolvers for business logic.
• Real-time with Subscriptions (WebSockets).
• Code Example: Sample resolver and schema.
Tools and Best Practices
• Schema-First Development: Define schema before coding.
• Error Handling: Standardize error responses.
• Performance: Use DataLoader for batching and caching.
• Security:
• Use depth/complexity limiting tools.
• Secure authentication and authorization.
• Versioning: Maintain compatibility.
Challenges
• Overhead in learning curve.
• Complexity in schema design for large teams.
• Managing real-time data at scale.
Thank You

You might also like