Please enable JavaScript.
Coggle requires JavaScript to display documents.
Modern web application (lecture 1: ECMA 6 (Spread vs Rest (Spread : When…
Modern web application
lecture 1: ECMA 6
Spread vs Rest
-
- Rest: When using rest arguments, you are collapsing all remaining arguments of a function into one array:
let vs var: https://goo.gl/xQpCj9
- var is scoped to the nearest function block
- let declared in their enclosing block
-
-
Filter and Map:
- Filter: students.filter(student => student.grade >= 6);
- Map: students.map(obj => obj.name;); // [ 'Anna', 'John', 'Maria' ]
-
-
Reduce: const total = students.reduce((sum, student) => sum+student.grade, 0);
-
Node JS: Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
LECTURE 2
-
process.nextTick(callback): it adds the callback into the nextTick queue after the current operation completes and before the event loop continues
which means it runs before any addition IO events or timers fire in the subsequent ticks of the event loop
brief
-
Event-driven, non blocking io
Tradition : blocking
Non blocking IO
-
-
-
-
-
-
Lecture 3
NPM, modules
Modules
-
if we created the js file , it should be a module
- add ./ to make it look into local location for the js file
- pass the filename means require a node core module
if we pass a folder without filename, it will look into the file with index.js name
works
-
return module.exports, export is a reference to module.exports
node will wrap into: (function (exports, require, module, filename, dirname) { let export = module.export;});
-
STEP:
- resolve,
- load,
- wrap,
- evaluate,
- cache
-
-
-
-
Buffer and Stream
Buffer: a chunk of memory allocated outside V8, limited in size and we can not resize allocated buffer
- Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the v8 heap, the size of the Buffer is established when it is created and cannot be changed.
- Buffer data are saved in binary, so it can be interpreted in many ways depending on the length of characters. we need to specify the char-endcoding when we read data from Buffer. if we dont specify the encoding when receive a Buffer object with the data represented in a hex format in the console
- slice: buffer.slice(10,20)
copy: buffer.copy(targetBuffer, targetStart, sourceStart, sourceEnd)
Stream: a sequence of data made available over time. Pieces of data that eventually combine into a whole
- collection of data that might not be available all at once and dont have to fit in memory. streaming the data means an application processes the data while it's still receiving it.
- This is useful for extra large datasets, like video or database migrations
Type:
- Reable(fs.createReadStream)
- Writable(fs.createWriteStream)
- Duplex(socket)
- Transform(zlip)
pipe: connect 2 streams, available on readable streams
File: require('fs'); fs.readFile, fs.readFileAsyn
lecture 4: package, npm, asyn, promise, generator and observables
-
Reading the Post data
-
- post serve our post data in small chunk (stream)
callback that upon the certain event
- there even are data(new chunk of data arrive) and end(all chunk data received)
- we need to tell the node js that which function is callback when these event occurs. by adding the listener to request
usage:
Asynchronous code
Promise :forbidden:
Definition :no_entry:
- object is used for asynchronous computation
- a promise object represent value which maybe available now, future or never
- new Promise (function(resolve, reject ){...}); :warning:
- promise has 2 method then and catch, the method will call base on the state of promise object
- Promise.Prototype.then()
- Promise.Prototype.catch()
- fetch("url link") // return a Promise
3 status :red_cross:
- pending,
- fulfilled,
- rejected
usage :pen:
-
Fetch
Fetch all
-
Async & Await (ES7, Node 8)
Definition :check:
- await go with async
- works like generator
- async always return the promise
-
-
-
-
Routing
-
-
lecture 5,6: Express js
HTTP access control
ajax
-
-
Same orgin policy
allow scripts running in a browser to only make XHR requests to pages on the same domain.
cookies: are not set automatically from ajax response.
ajax calls only send cookies if the url you are calling from the same domain as you are calling the script
- send cookies in cross domain ajax call
xhrFields: withCredentails is true
REST
- method: GET, POST, ....
- stateless vs stateful
Express js
- Web framework
- core node.js http and connect components (middleware)
Feature
- Parsing HTTP request bodies
- Extract URL parameter
- Parse cookie
- Manage sessions
- organize routes with chain of if condition base on the url path and http methods
- give back the proper response header base on the data type
- catch error
Application Structure
DEFINITION: :check:
- useful pattern that allows developer reuse code within their application and share to other in the form of NPM module.
- Middleware functions 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.
1 -- Application Middleware :check: link
- app.use(optional string path, mandatory callback fn)
app.use('/register', function(req, res, next) {return next();})
- app.method(path, [callback...], callback); the callback that we pass to get() or post() methods are called request handlers because they take the requests, process them and write to the response objects
ex: app.get('/api/1.0', function(req, res, next)) {next();}
app.get('/api/1.0', function(req, res)) {res.end();}
app.post('/api/v1/register', function(req, res){//...})
- app.all(): like app.method(), except it matches all HTTP verbs
- request handlers: are functions with req and res parameter, we can use next() for control flow,
- next() go to the next request handler function , could be the same url route
- next('route'): skip current route and go to the next one
- next('stElse'): go to the error handler
- use the return keyword: come back to the original execution stack
4 -- Built-in middleware :check: link
- express.static: serving static resource
it enabled pass-through requests for static assets, provide the path and return a middleware function files will be read from that path and will be streamed immediately to response.
- Ex: app.use(express.static(dirname + '/public'));
app.use('/css', express.static(dirname + 'public/css'));
app.use('/img', express.static(dirname + 'public/images'));
app.use('/js', express.static(dirname + 'public/javascripts'));
// hide your real server structure file
- express.urlencoded parses incoming requests with URL-encoded payloads
- express.json
Middleware order :star:
- express session follow cookie
- CSRF: require express-session
- Middle statement before route.
body-parse :red_flag: handle http POST request
- request -> cookie-parse -> errorhandle -> route
- json(), urlencoded(), raw(), text()
- using body-parser only for certain route
Useful middlewares :recycle:
- require('compression'),
- require('morgan'),
- require('cookie-parse'),
- require('express-session'),
- require('csurf'),
- require('connect-timeout'),
- require('serve-favicon'),
- require('serve-index'),
- require('response-time'),
- require('vhost')
-
security :no_entry:
csrf :red_flag: matching the incoming value from requests
- the csrf: preceded by cookie-parse and express-session
- check standard headers to verify the request is same origin: check origin header, check referer header
- check csrf token
- usage:
- var csrf = require('csurf');
app.use(csrf());
- app.use (function (req, res, next){
response.locals.csrftoken = request.csrfToken();next();
})
- in template: <input type="hidden" name="_csrf" value="<%=csrftoken%>">
HTTP security header :red_cross:
Helmet is the collection of security-related middleware
- usage:
var helmet = require('helmet');
app.use(helmet);
CORS :forbidden: linkto
app.use(function(req, res, next){res.header("Access-Control-Allow-Origin","*"); next})
Access-Control-Allow-Method
Access-Control-Allow-Header
server side input validation :smiley:
check password, email format
-
-
-
- etags :warning: caching tool, give the unique identifier for the content on a give url, in other word, if content does not change the specific url, the etag will the same and the browser will use the cache
default value is true(weak, the response is sematically), false (no e tags), strong (strong etag the response is byte-to-byte)
- Evironment
(production, test, stage, preview, development)
app.set('env', 'development');
- view cache
(is true, allow template compilation caching. default of production is true)
- view
(the view has an absolute path to your directory)
ex: app.set('views', path.join(__dirname, 'template'))
- view Engine
(the ve hold the template file extension ejs or pug)
- trust proxy
(X-Forwared-* header)
- case sensitive routing: to deal with upper case on url
- strict routing: it deals with cases of trailing slashes in urls
setting x-power-by :no_entry:
set HTTP header
app.set('x-powered-by', false);
- query parse
parse the data sent in the url after the question mark
- subdomain offset
it control the value returned by the req.subdomain property
-
- template engine: related to view
allow us use difference template language, rendering and compile
use:
- specify the file/engine extension (ejs or jade)
- path to your views
- consolidate(use with swig)
-
-
-
3 -- Error-handling middleware :check: link
- 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)):
usage :check:
- use try catch and no asynchronus calling
- app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
2 -- Router-level middleware :check: link works in the same way as application-level middleware, except it is bound to an instance of express.Router().
var app = express();
var router = express.Router(options);
lecture 7,8,9: mongodb
-
-
structure :red_cross:
-
BSON :lock:
definition :recycle:
Binary Json, is a binary-encoded serialization of Json-like documents
-
-
-
Document database Model link
Definition :green_cross:
- MongoDB is an open-sourse document database that provides high performance, high availability, automatic scaling
- Non relational DB, stores BSON document
- Schemaless: two document dont have the same schema
-
-
midterm exam
-
-
-
- bien toan cuc db
- var ObjectID = require('mongodb').ObjectID;
-
-
-
Angular
angular core concept
-
-
-
Explain:
- component and template defined the view
- the dependency injector provides the service to a component
- Ex: the route service, let you define navigator among the views
-
-
-
Covered Query #
A covered query is a query that can be satisfied entirely using an index and does not have to examine any documents
- cursor.hint(index): Call this method on a query to override MongoDB’s default index selection and query optimization process. Use db.collection.getIndexes() to return the list of current indexes on a collection. #
-
-
update(query,update,option, callback)
findAndModify(query: <document>,sort,
remove, update, new , field, upsert, callback)
-