You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Due to the event-oriented nature of Node. Application is javascript app. nodejs will carry out to actions when
the request from visitors arrive simultaneously. and come back toevent loop waiting to the event to happen again
create folder demo1
copy text to file hellonode.js to editor
Recommend editor which support javascript
code editor
//Load HTTP module
var http = require("http");
//Create HTTP server and listen on port 8000 for requests
http.createServer(function (request, response) {
// Set the response HTTP header with HTTP status and Content type
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body "Hello World"
response.end('Hello World\n');
}).listen(8000);
// Print URL for accessing server
console.log('Server running at http://127.0.0.1:8000/')
Code import "http" module and create a srever "createserver()" listen on port 8000
createserver() take function as an argument a callback function. Function will invoked when HTTP request is received
Open Terminal and run code
node hellonode.js
Server running at http://127.0.0.1:8000/
use express library by import expresss module and create app with express()
listen for HTTP request on port 8000. app.get() function only responds to HTTP Get request with specified URL path ('/')
can calling function to return
open editor can copy code below
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(8000, function () {
console.log('Example app listening on port 8000!')
})
Express support routing to application endpoints respond to client request. supprt all HTTP method
Basic route can use (app.METHOD)
app.get() will handle get request and app.post() handle post request
app.all() will handle all request
that response will handle from callback function
var express = require('express')
var app = express()
// 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')
})
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})
Route paths
Route path , in combination with request will define the endpoint
on request.
Route path can be
String
string patterns or reqular expressions
combination ?, +, *, and ()
Example
app.get('/', function (req, res) {
res.send('root')
})
app.get('/about', function (req, res) {
res.send('about')
})
app.get('/random.text', function (req, res) {
res.send('random.text')
})
create path match acd or abcd
app.get('/ab?cd', function (req, res) {
res.send('ab?cd')
})
match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', function (req, res) {
res.send('ab+cd')
})
match abcd, abxcd, abRANDOMcd, ab123cd,
app.get('/ab*cd', function (req, res) {
res.send('ab*cd')
})
match /abe and /abcde
app.get('/ab(cd)?e', function (req, res) {
res.send('ab(cd)?e')
})
match anything with an “a” in the route name.
app.get(/a/, function (req, res) {
res.send('/a/')
})
match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.
app.get(/.*fly$/, function (req, res) {
res.send('/.*fly$/')
})
Route parameter
pass parameter in URL segments. Route capture the values by their position in url. and populated in req.params
with name of the route parameter and value
Route act as middle ware pass handle request to next function.
single call back function
app.get('/example/a', function (req, res) {
res.send('Hello from A!')
})
more than one call back
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
And array of callback functions
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
compination of independent fucntions and arrays of the function
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})
Response methods
methos on response object (res)
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.
app.route()
you can create chainable route handle same path but different http method
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
express.Router()
use Router class to create modular, mountable route handlers. Router instance is middleware of routing system.
create modular by create router file name birds.js
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
Load to 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.
Summary
You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.