Express js

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Whats makes Node js so great?

Node JS: 1. It's a JavaScript runtime built on Chrome's V8 JavaScript engine. - Both Node and the JS that is executed inside of your browser are running on the same engine. It's an open source engine that takes JS code and compiles it to much faster machine code, this is what makes Node.js so fast! 2. Uses an event-driven, non-blocking I/O model that makes it light weight & efficient 3. Node.js' package ecosystem, npm, is the largest ecosystem if open source libraries in the world

Route parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys. Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 req.params: { "userId": "34", "bookId": "8989" } To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) })

Route Handlers

https://expressjs.com/en/guide/routing.html

What is a module in node js?

- A module is a file/library which performs a specific tasks in an application. - we can make our own modules, which can import modules into our application some come inbuilt in node. - they make our application modular that has many advantages including code re-usability, ease of maintenance and debugging e.t.c.

Event Programming

Event Driven Programming: - is a computer programming paradigm in which control flow of the program is determined by the occurrence of events. - these events are monitored by code known as an event listener that, if it detects that its assigned event has occurred, runs an event "handler", typically a callback function or method. - this handler deals with the event by responding to it with program code.

Routing in express js.

Routing refers to determining how an application responds to a client's request. Each route may have one or more handler functions which are executed when a route is matched. Route definition app.[METHOD](<PATH> <HANDLER>) Whereby: - app is an instance of express. - method is an http request verb or method in lowercase. - path is a path / route on the server. - route handler is a function/s that is executed when the route is matched.

Express JS

- the most popular Node js framework. - it provides mechanism to: 1. Write handlers for requests with different HTTP verbs at different URL paths (routes). 2. Integrate with "view" rendering engines in order to generate responses by inserting data into templates. 3. Set common web application settings like the port to use for connecting, and the location of templates that are used for rendering the response. 4. Add additional request processing "middleware" at any point within the request handling pipeline.

app.all( )

A special routing method, app.all( ), used to load middleware functions at a path for all HTTP request methods. For example, the following handler is executed for requests to the route "/secret" whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the http module. app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...') next() // pass control to the next handler })

What is Node JS?

Node JS is an open source, cross-platform environment that allows developers to create server-side tools and applications in JavaScript.

Using express.Router

var express = require('express') var router = express.Router() // middleware that is specific to this router router.use(function timeLog (req, res, next) { console.log('Time: ', Date.now()) next() }) // define the home page route router.get('/', function (req, res) { res.send('Birds home page') }) // define the about route router.get('/about', function (req, res) { res.send('About birds') }) module.exports = router Then, load the router module in the app: var birds = require('./birds') // ... app.use('/birds', birds) The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.

Using modules in Node JS

- Use a function called require( ): const express = require('express'); - require ( ) will let us do 3 things: 1. load in modules that come with Node.js — example: http module, FS module 2. load in third party libraries that allows us to write less code — example: express.js 3. require our very own files. This will allow us to break up our application to multiple smaller files which is essential for building real-world apps.

Route methods

A route method is derived from one of the HTTP methods, and is attached to an instance of the express class. These routing methods specify a callback function (sometimes called "handler functions") called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function. In fact, the routing methods can have more than one callback function as arguments. With multiple callback functions, it is important to provide next as an argument to the callback function and then call next( ) within the body of the function to hand off control to the next callback.

What happens when an express application is instantiated?

A series of events occur: The express application first creates a web server the web server then listens for requests at a defined port using the app.listen( ) method. The express application then provides an interface to communicate with the server. Whereas http defines how the client and server communicate. An express application itself is a series of middleware function calls. 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. The next middleware function is commonly denoted by a variable named next. Middleware functions can: 1. Execute any code. 2. Make changes to the request-response objects. 3. Terminate the request-response-cycle. 4. Call the next middleware function in the stack. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Web Framework

A web framework or web application framework is a software framework/library that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications.

Types of middleware functions

An Express application can use the following types of middleware: Application-level middleware Router-level middleware Error-handling middleware Built-in middleware Third-party middleware You can load application-level and router-level middleware with an optional mount path. You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.

Application level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase. This example shows a middleware function with no mount path. The function is executed every time the app receives a request. var app = express() app.use(function (req, res, next) { console.log('Time:', Date.now()) next() }) This example shows a middleware function mounted on the /user/:id path. The function is executed for any type of HTTP request on the /user/:id path. app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method) next() }) This example shows a route and its handler function (middleware system). The function handles GET requests to the /user/:id path. app.get('/user/:id', function (req, res, next) { res.send('USER') }) Here is an example of loading a series of middleware functions at a mount point, with a mount path. It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the /user/:id path. app.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('Request Type:', req.method) next() })

Error handling middleware

Error-handling middleware Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)): app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') })

NPM

It is the official package manager for Node and is bundled & installed automatically with the environment.

Node Event Loop

Node.js is a single threaded application but it support concurrency via the concepts of events and callbacks. As every API of Node.js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses the observer pattern. A Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which then signals the event listener function to get executed.

Application level middleware continued.

Route handlers enable you to define multiple routes for a path. The example below defines two routes for GET requests to the /user/:id path. The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle. This example shows a middleware sub-stack that handles GET requests to the /user/:id path. app.get('/user/:id', function (req, res, next) { console.log('ID:', req.params.id) next() }, function (req, res, next) { res.send('User Info') }) // handler for the /user/:id path, which prints the user ID app.get('/user/:id', function (req, res, next) { res.end(req.params.id) }) To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions. This example shows a middleware sub-stack that handles GET requests to the /user/:id path. app.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next() }, function (req, res, next) { // send a regular response res.send('regular') }) // handler for the /user/:id path, which sends a special response app.get('/user/:id', function (req, res, next) { res.send('special') }) Middleware can also be declared in an array for reusability. This example shows an array with a middleware sub-stack that handles GET requests to the /user/:id path function logOriginalUrl (req, res, next) { console.log('Request URL:', req.originalUrl) next() } function logMethod(req, res, next) { console.log('Request Type:', req.method) next() } var logStuff = [logOriginalUrl,

Route paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions. The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths. If you need to use the dollar character ($) in a path string, enclose it escaped within ([ and ]). For example, the path string for requests at "/data/$book", would be "/data/([\$])book".

Router level middleware

Router-level middleware Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router(). var router = express.Router() Load router-level middleware by using the router.use() and router.METHOD() functions. The following example code replicates the middleware system that is shown above for application-level middleware, by using router-level middleware: var app = express() var router = express.Router() // a middleware function with no mount path. This code is executed for every request to the router router.use(function (req, res, next) { console.log('Time:', Date.now()) next() }) // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path router.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('Request Type:', req.method) next() }) // a middleware sub-stack that handles GET requests to the /user/:id path router.get('/user/:id', function (req, res, next) { // if the user ID is 0, skip to the next router if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next() }, function (req, res, next) { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page router.get('/user/:id', function (req, res, next) { console.log(req.params.id) res.render('special') }) // mount the router on the app app.use('/', router)

Built-in middleware

Starting with version 4.x, Express no longer depends on Connect. The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions. Express has the following built-in middleware functions: express.static serves static assets such as HTML files, images, and so on. express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+ express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+

Error Handling in an express application

Study this topic resource: https://expressjs.com/en/guide/error-handling.html

What is package.json?

The best way to manage locally installed npm packages is to create a package.json file. A package.json file affords you a lot of great things: 1. It serves as documentation for what packages your project depends on. It allows you to specify the versions of a package that your project can use using semantic versioning rules. 2. Makes your build reproducible which means that its way easier to share with other developers.

Express Router

The express.Router class is used to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a "mini-app". In simple terms its used to group related routes.

Examples of route methods

The following code is an example of routes that are defined for the GET and the POST methods to the root of the app. // GET method route app.get('/', function (req, res) { res.send('GET request to the homepage') }) // POST method route app.post('/', function (req, res) { res.send('POST request to the homepage') })

Response methods

The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging. Method Description res.download( ) Prompt a file to be downloaded. res.end( ) End the response process. res.json( ) Send a JSON response. res.jsonp( ) Send a JSON response with JSONP support. res.redirect( ) Redirect a request. res.render( ) Render a view template. res.send( ) Send a response of various types. res.sendFile( ) Send a file as an octet stream. res.sendStatus( )Set the response status code and send its string representation as the response body.

Router level middleware continued.

To skip the rest of the router's middleware functions, call next('router') to pass control back out of the router instance. This example shows a middleware sub-stack that handles GET requests to the /user/:id path. var app = express() var router = express.Router() // predicate the router with a check and bail out when needed router.use(function (req, res, next) { if (!req.headers['x-auth']) return next('router') next() }) router.get('/', function (req, res) { res.send('hello, user!') }) // use the router and 401 anything falling through app.use('/admin', router, function (req, res) { res.sendStatus(401) })

Third-party middleware

Use third-party middleware to add functionality to Express apps. Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level. The following example illustrates installing and loading the cookie-parsing middleware function cookie-parser. $ npm install cookie-parser var express = require('express') var app = express() var cookieParser = require('cookie-parser') // load the cookie-parsing middleware app.use(cookieParser())


Set pelajaran terkait

Chapter 7 - External Competitiveness

View Set

Community Health Test 1 - Ch 1, 2, 3, 5, 9, 11, 12, 24

View Set

Money And Banking Final Study Guide

View Set