Express

From Training Material
Jump to navigation Jump to search


Express exercises

Node with express

Making 'express.js' project
----------------------------------------
sudo npm install -g express express-generator
express -e my-express-project
cd my-express-project
npm install
npm start
# navigate to http://localhost:3000/ in your web browser
----------------------------------------







Creating simple router in express.js

1. First, let's create a new route for all our API requests.
Create a new file called '/routes/api.js' ;
inside this file, we will define two new routes:
----------------------------------------
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
  res.send('API is running');
});

router.get('/:param', function(req, res, next) {
  var params = req.params;
  var query = req.query;
  Object.assign(params, query);
  res.json(params);
});
module.exports = router;
----------------------------------------

2. Next, we will update our '/app.js' configuration to import this new route, and
provide it to Express as middleware using the use command:
----------------------------------------
(...)
var api = require('./routes/api');
var app = express();
(...)
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
(...)
----------------------------------------

3. Finally, we must restart our Express server. Now, when we visit
'localhost:3000/api' , we will see the API is running text; if we visit
'localhost:3000/api/foobar?search=barfoo' , we will see a JSON response:
{
  "param":"foobar",
  "search":"barfoo"
}







Implementing static file serving in Express

1. First, let's build our Angular application by running the Angular-CLI build command in our project directory:
----------------------------------------
cd your_angular_app_path
ng build
----------------------------------------

2. Next, let's create a new '/routes/angular.js' route in our Express project, to configure serving our Angular application. We will need to define a relative route from this project to our Angular project using Node.js's core path module:
----------------------------------------
var path = require('path');
var express = require('express');
var router = express.Router();

var angularBuildPath = path.resolve(__dirname, '../../my-angular-project/dist');
router.use(express.static(angularBuildPath));
router.get('*', (req, res, next) => {
  if (req.url.startsWith('/api')) return next();
  res.sendFile(path.join(angularBuildPath, 'index.html'));
});

module.exports = router;
----------------------------------------

3. We will have to update our '/app.js' Express configuration to load our new route configuration. Since it will serve most of the content for our application, we will place it before our API configuration. We'll also remove the 'index' and 'user' routes that were generated when we originally created the project with express-generator:
----------------------------------------
(...)
var api = require('./routes/api');
var angular = require('./routes/angular');
(...)
app.use('/', angular);
app.use('/api', api);
(...)
----------------------------------------

4. Almost there (-:
Update our error handler in '/app.js' so that it will instead serve JSON error
messages to us when there is an unresolved request:
----------------------------------------
(...)
app.use('/', angular);
app.use('/api', api);
(...)
app.use(function(req, res) {
  var error = new Error('Not Found');
  res.status(404).json({
    status: 404,
    message: error.message,
    name: error.name
  });
});
module.exports = app;
----------------------------------------

5. Restart your Express server and navigate to 'localhost:3000/' . 
You will see your Angular application load.
Navigating to 'localhost:3000/api/' will still serve the API status page.

Adding Bootstrap

0. Install Bootstrap via npm
npm install bootstrap@3.4.1


1. We will have to update our '/app.js' Express configuration.
...
app.use(express.static(path.join(__dirname, 'public')));
// Bootstrap part, step 1
app.use(express.static(__dirname + '/node_modules/bootstrap/dist'));

app.use('/', angular);
app.use('/api', api);
...


2. Then we need to add Bootstrap's "css" and "js" references in our main html template (usually it's "index.html").
<!-- jQuery reference -->
...
<!-- Bootstrap, part 2 -->
<script language="javascript" src="js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
...
<!-- our custom js, which is using other libraries, etc -->


3. Restart your Express server and navigate to localhost:3000/ .


4. Add some "css" classes from Bootstrap, restart server again and enjoy!
(-8

Pesel app

Make it as:

  • angular5 app
  • vue.js app
  • react.js app
  • ember.js app
  • extension to node3 or node4
  • extension to ts-node-starter
<html>
	<head>
	    <title>pesel</title>
	    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	</head>
	<body>
	    <form id="testy" action="#">
	        PESEL: <input type="text" id="pesel" value="59112304975">
	        NIP: <input type="text" id="nip" value="8652402585">
	        DOB: <input type="text" id="dob">
	    </form>

	    <script type="text/javascript">
/**
 * Invoking declared functions
 */
jQuery(document).ready(function() {
  updateDateOfBirthFromPesel();  
  checkNIP();
});

/**
 * Gets proper date of birth from pesel
 *
 */
function updateDateOfBirthFromPesel() {
  jQuery("#pesel").focusout(
  	function(){
		var peselFromForm = jQuery(this).val().trim();
		var peselv = peselValid(peselFromForm);
		if ( !peselv ) {
			if ( !jQuery("#checkpesel").length ){
				jQuery("#testy").prepend('<p id="checkpesel" style="color:red; font-size:24px;">Invalid PESEL number!</p>');
			}
		} else {
			jQuery("p#checkpesel").remove();
			var yearFromPesel = peselFromForm.substr(0, 2);
			var monthFromPesel = peselFromForm.substr(2, 2);
			var dayFromPesel = peselFromForm.substr(4, 2);
			var countedFromPesel = peselDfp(yearFromPesel, monthFromPesel);
			var dateOfBirth = countedFromPesel['year'] + '-' + countedFromPesel['month'] + '-' + dayFromPesel;
			jQuery("#dob").val(dateOfBirth);
		}
  });
}

/**
 * Adds invalid nip error message
 * 
 */ 
function checkNIP(){
	jQuery("#nip").focusout(
		function(){
	var nip = jQuery(this).val().trim();
	var nipv = nipValid(nip);
		if ( !nipv ) {
			if ( !jQuery("#checknip").length ){
			jQuery("#testy").prepend('<p id="checknip" style="color:red; font-size:24px;">Invalid NIP number!</p>');
			}
		} else {
			jQuery("p#checknip").remove();
		}
  });
}
/**
 * Transforms the year and month from PESEL into real date
 * 
 */
function peselDfp(yfp, mfp){
	var dfp = [];
	var age1800_1899 = ["81","82","83","84","85","86","87","88","89","90","91","92"];
	var age1900_1999 = ["01","02","03","04","05","06","07","08","09","10","11","12"];
	var age2000_2099 = ["21","22","23","24","25","26","27","28","29","30","31","32"];
	var age2100_2199 = ["41","42","43","44","45","46","47","48","49","50","51","52"];
	var age2200_2299 = ["61","62","63","64","65","66","67","68","69","70","71","72"];

	function checkCentury(m) {
		return m === mfp;
	}

	if ( age1800_1899.find(checkCentury) ) { dfp['year'] = 18 + yfp; dfp['month'] = age1900_1999[ age1800_1899.indexOf(mfp) ]; }
	if ( age1900_1999.find(checkCentury) ) { dfp['year'] = 19 + yfp; dfp['month'] = mfp; }
	if ( age2000_2099.find(checkCentury) ) { dfp['year'] = 20 + yfp; dfp['month'] = age1900_1999[ age2000_2099.indexOf(mfp) ]; }
	if ( age2100_2199.find(checkCentury) ) { dfp['year'] = 21 + yfp; dfp['month'] = age1900_1999[ age2100_2199.indexOf(mfp) ]; }
	if ( age2200_2299.find(checkCentury) ) { dfp['year'] = 22 + yfp; dfp['month'] = age1900_1999[ age2200_2299.indexOf(mfp) ]; }

	return dfp;
}
/**
 * Validates NIP, Polish VAT NO
 * 
 */
function nipValid(nip) {
        var weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
        nip = nip.replace(/[\s-]/g, '');

        if (nip.length === 10 && parseInt(nip, 10) > 0) {
                var sum = 0;
                for(var i = 0; i < 9; i++){
                        sum += nip[i] * weights[i];
                }
                return (sum % 11) === Number(nip[9]);
        }
        return false;
}

/**
 * Validates PESEL, Polish social no
 * 
 */
function peselValid(pesel){
	var weights = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7];
	pesel = pesel.replace(/[\s-]/g, '');

    if ( pesel.length === 11 && parseInt(pesel, 11) > 0 ) {
        var sum = 0;
        for(var i = 0; i < 10; i++){
            sum += pesel[i] * weights[i];
        }
        return (sum % 10) === Number(pesel[10]);
    }
    return false;
}
	    </script>
	</body>
</html>

Docker with node