Skip to content

Instantly share code, notes, and snippets.

@iraklisg

iraklisg/expressalicea.js

Last active Jul 20, 2017
Embed
What would you like to do?
express mini docs
const express = require('express'); // exporting the createApplication() in lib/express.js that returns a function which returns a function which has attached extra properties
const app = express(); //this also returns a function with some extra properties attached
const port = process.env.PORT || 3000; // in production server I will set the env variable PORT so it wont be 3000
app.get('/hello', (req, res) => {
res.send('Hello world'); // or I can send a JSON file res.json({firstname: 'John', lastname: 'Doe'})
}); //if a request comes in and url =xxx and verb is GET call the callback and passes an express request and response which are node's req and res on steroids
/**
* ***********************************************************
* Passing route params (does pattern matching)
* **********************************************************
*/
app.get('/person/:firstname/', (req, res) => {
let firstname = req.params.firstname;
res.json({
firstname: firstname,
});
});
/**
* **********************************************************************
* STATIC files (css, images, html; no need to be processed by code
* before downloaded) and MIDDLEWARE (code that sits between two
* layers of software; in express between request and response,
* providing automatic responses to particular requests)
* **********************************************************************
*/
// There are plenty of middleware in expressjs.com/resources/middleware (cookie.parser, passport, )
// I need to deal with static files requested to be downloaded by the browser
// express provides use to use MIDDLEWARE, i.e. to match a particular URL with a function
app.use('/assets', express.static(__dirname + '/public')); // whenever you have a request for assets/* look in /public folder for a file with the same name and stream the response back
// If I don't provide a URL, then the middleware (function) is applied to all routes
// E.g. at the beginning: app.use(globalMiddleware())
app.get('/', (req, res, next) => {
res.send('<html><head><link href=assets/style.css type=text/css rel=stylesheet /></head><body><h1>Hello world!</h1></body></html>');
next(); //this will run the next middleware
});
// Building custom middleware
app.use('/', (req, res, next) => { // whatever matches the '/*' pattern, e.g. '/', '/foo'
// My own code (middleware) here...
console.log((`Request URL: ${req.url}`));
next(); // run the next middleware (app.get(), app.post() methods are essentially middlewares so I can run the next route; express.static() also invokes next() in its scope)
});
/**
* **********************************************************************
* TEMPLATES and TEMPLATE ENGINES
* **********************************************************************
*/
// You have to plug in your own template engine (yarn add jade )
// WARNING: some template engines cache the content and update the cache when file is changed to be faster
// set the engine app.set('view engine', 'jade')
app.set('view engine', 'pug');
app.set('views', __dirname + '/views'); //overwrite default views folder
app.get('/lovejade', (req, res) => {
res.render('index', {title: 'Hey you', message: 'Out there on the road'}); // by default looks for the html files the 'views' directory
});
/**
* **********************************************************************
* QUERY STRINGS and POST DATA
* **********************************************************************
*/
/*
Dealing with query strings
*/
app.get('/lovejade1', (req, res) => {
let queryString = req.query.foo; // for fetching querystring from localhost/lovejade1?foo=bar
res.render('index', {title: 'Hey you', message: queryString}); // by default looks for the html files the 'views' directory
});
/*
Dealing with POST data
*/
// EXPRESS PARANOIA: I need a request body parser (i.e. middleware) to install in order to parse the POST request body
// The parser will read the body of HTTP request, and attach data to req.body property; then the callback is called
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({extended: false}); //create 'application/x-www-form-urlencoded' parser
const jsonParser = bodyParser.json(); // creates an 'application/json' parser
// ##COOOLLL: I can use this parser (i.e middleware) as a third option in app.post instead of app.use('URI', parser)
// This will filter request with both URI and VERB!
app.post('/lovejade1', urlencodedParser, (req, res) => { // the middleware will be called before (req, res) => {}
let data = req.body.foo; // for POST data {'foo': 'bar'}
res.render('index', {title: 'Hey you', message: data}); // by default looks for the html files the 'views' directory
});
app.listen(port); //what that returns is an http server running by creating a createServer object and invoking it
/**
* **********************************************************************
* ROUTING
* **********************************************************************
*/
// Break down routes using app.use()
// i.e use a middleware and attach it to a path app.use('/', middleware)
/*
---------------------------------------------
in users.js route file
--------------------------------------------
var express = require('express')
var router = express.Router();
router.get('/', (req, res, next) => { // if I said "/baz" it will matched the parent /users/baz/*
res.send('respond);
});
module.exports = router; // router is basically a middleware!
--------------------------------------------
*/
/*
---------------------------------------------
in app.js entry point
--------------------------------------------
const userRoutes = require('./routes/users');
app.use('/users', userRoutes) // this will match all routes (because of router.get('/', ...) under the "/user" domain i.e. "/user/foobar"
--------------------------------------------
*/
/**
* **********************************************************************
* STRUCTURE
* **********************************************************************
*/
// I have a controllers directory with app
/*
---------------------------------------------
in myController.js file
--------------------------------------------
const parser = require('parser') // require all dependencies (require caches so it won't cost me anything :))
module.exports = function (app) { //TODO try using arrow functions
//some code...
app.get(...)
app.delete(...) // the app instance is passed by reference and we mutate it by attaching extra properties
}
--------------------------------------------
*/
/*
---------------------------------------------
in app.js.entry point
--------------------------------------------
var myController = require("./myController")
...
myController(app); // pass the "app" to module by reference and the function will add to it .get and .delete properties
--------------------------------------------
*/
// app.listen = function listen () {
// var server = http.createServer(this); <-- this is the queryListener
// return server.listen.apply(server, arguments);
// };
// yarn global add <package>
// Adding to $PATH...
// > We've added the following to your /home/ira/.bashrc
// > If this isn't the profile of your current shell then please add the following to your correct profile:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment