w4 Flashcards
Express.js app.set
to define a value based on key and value
Express.js app.get
app.get to retrieve the value based on the key/name of the setting.
Third-party middleware
invoked by express for tasks- has access to response and request objects
Morgan
HTTP request logger middleware for node.js.
It generates logs automatically for any request being made.
It has a set of predefined formats such as tiny, short, common, etc
can intercept request and do pre-processing through middleware by?
app.use()
app.use(function (req, res, next) {
req.timestamp = new Date().toISOString();
next();
});
purpose of next function in middleware preprocessing
The next() function represents the next middleware function to be executed. If you choose not to call function next(), the request will be left hanging.
Parsing app for POST method
// parse application/x-www-form-urlencoded
app.use(express.urlencoded({extended: true}));
// parse application/json
app.use(express.json())
req.body
Extracting for post requests using body-parser middleware
app.post(‘/data’, function (req, res) {
console.log(req.body.username);
console.log(req.body.userage);
res.send(‘Thank You’)
})
GET vs POST requests
GET request is used to get data from the server, such as HTML files. Express.js handles GET requests by using app.get (lines 9-11).
POST request is used to send data from the client to the server such as username and password fields. Express.js handles POST requests by using app.post (lines 12-17)
Rendering engine
Use static files in app
Runtime-> engine will replace template values with actual values and transform to HTML file
design dynamic HTML files
Most popular view engine
EJS (Embedded JS)
EJS?
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
No religiousness about how to organize things.
No reinvention of iteration and control-flow. It’s just plain JavaScript
EJS engine config
app.engine(‘html’, require(‘ejs’).renderFile);
app.set(‘view engine’, ‘html’);
res.render() ?
method each time you need to send an HTML file to a client.
renders a view and sends the rendered HTML string to the client.
res.render() optional parameters
locals, an object whose properties define local variables for the view.
callback, a callback function. If provided, the method returns both the possible error and rendered string but does not perform an automated response. When an error occurs, the method invokes next(err) internally