Sunday, August 20, 2017

Express

Express




    πŸ’₯Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications.

     πŸ’₯Following are some of the core features of Express framework −
  • Allows to set up middle wares to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.
  • Allows to dynamically render HTML Pages based on passing arguments to templates.

    πŸ’₯Install the Express framework globally using NPM so that it can be used to create a web application using node terminal.
           npm install express --save 

    πŸ’₯we should install the following important modules along with express 

  • body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
            npm install body-parser --save

  • cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
           npm install cookie-parser --save

  • multer − This is a node.js middleware for handling multipart/form-data.
           npm install multer --save

     πŸ’₯Request & Response

              Express application uses a callback function whose parameters are request and response objects.

          app.get('/',function()
                 {

                  })

  •  Request Object − The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers.
  • Response Object − The response object represents the HTTP response that an Express app sends when it gets an HTTP request.

Monday, August 14, 2017

Heroku and mLab

Deployment Steps For Heroku & mLab
   

  1. Signup for Heroku
  2. Signup for mLab
  3. Create DB notable in mLab
  4. Add user in mLab
  5. Update DB url in node server
mongodb://<dbuser>:<dbpassword>@ds149122.mlab.com:49122/notable
     6. Test notable app



8. Add (specify version of node) to package.json

"engines": {
    "node": "6.10.1"
 }

9. Add Procfile to root
web: node server.js

10. Edit  /client from notes_routes.js to app.get('/',function(req, res) {

11. Make Common Base URL on script1.js and script2.js

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
console.log(baseUrl);

Add baseUrl instead of http://localhost:8000for all 4 CRUD methods.


11. Add .gitignore file to root
/node_modules
npm-debug.log
.DS_Store
/*.env

12. Change Port  on server.js
const port = process.env.PORT || 8000;

10. Build and run locally
npm install
heroku local web
12. Deploy your application to Heroku
git add .
git commit -m "first commit"
heroku login
Enter your Heroku credentials.
...

heroku create ukifunwork2byname

git push heroku master

Optional  (if above fails)- Add heroku git remote
heroku git:remote -a yourapp
And retry git push heroku master

heroku open

For Logging
heroku logs --tail

Tic-Tac-Toe

TIC-TAC-TOE


πŸ’•Add a file named index.js in the src/ folder with Js code.

          import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';

      class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {/* TODO */}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}



ReactDOM.render(
  <Game />,
  document.getElementById('root')
);



πŸ’•In particular, we have three components:

  • Square
  • Board
  • Game
The Square component renders a single <button>, the Board renders 9 squares, and the Game component renders a board with some placeholders that we'll fill in later. None of the components are interactive at this point.

     
πŸ’•passing some data from the Board component to the Square component.

   class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {this.props.value}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={i} />;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}


ReactDOM.render(
  <Game />,
  document.getElementById('root')
);
    

                 

Tic-Tac-Toe

Tic-tac-toe

 

πŸ’•If you want to do Tic-tac-toe, here are the steps to follow:

    πŸ’• Make sure you have a recent version of node js installed.
     πŸ’•Follow the installation instructions to create a new project.
         
             πŸ‘‰ npm install -g create-react-app
                 create-react-app my-app

                 cd my-app
                 npm start

         

  πŸ’•Delete all files in the src/ folder of the new project.
  πŸ’• Add a file named index.css in the src/folder with css code.
      
     πŸ‘‰ body {
  font: 14px "Century Gothic", Futura, sans-serif;
  margin: 20px;
}

ol, ul {
  padding-left: 30px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.status {
  margin-bottom: 10px;
}

.square {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.square:focus {
  outline: none;
}

.kbd-navigation .square:focus {
  background: #ddd;
}

.game {
  display: flex;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}




Heroku

Heroku

πŸ’™Heroku is a cloud platform as a service supporting several programming languages that is used as a web application deployment model.


1.How to use Heroku

  1. Download the Heroku Toolbelt.
  2. Login: heroku login.
  3. Add your public key: heroku keys:add.
  4. Pull down your current application heroku git:clone -a app-name.
  5. Make your improvements.
  6. Git add and commit your changes.
  7. Push back to heroku: git push heroku master.


 2.Advantages in Heroku

  • Heroku is easy to get started.
  • Heroku is the cheapest option for a low traffic site
  • we don't have to add our credit card for payment at early stage.
  • They offer no of Dyno for upgrade and downgrade app instance
  • Database integration is pretty simple with PostgreSQL

 3.Disadvantages in Heroku
  • we have to pay very high, once we decide to handle more traffic.
  • we have to manually scale our application on hight traffic.
  • we can't login to your server via SSH(Secure Remote Login & File Transfer)

4.What is SSH protocol?

The protocol is used in corporate networks for: 
  • providing secure access for users and automated processes
  • interactive and automated file transfers
  • issuing remote commands
  • managing network infrastructure and other mission-critical system components.

Thursday, August 3, 2017

React js(codecademy course)

React js codecademy course


πŸ’–React.js is a JavaScript library.

 πŸ’–It was developed by engineers at Facebook.

πŸ’–Here are just a few of the reasons why people choose to program with React:
                      1.React is fast.
                      2.React is modular.
                      3.React is scalable.
                      4.React is flexible.
                      5. React is popular.


What is JSX?

πŸ’–JSX is not valid JavaScript. Web browsers can't read it!

πŸ’– It was written to be used with React. JSX code looks a lot like HTML.

JSX Elements
πŸ’–A basic unit of JSX is called a JSX element.

πŸ’–Here's an example of a JSX element:


<h1>Hello world</h1>
πŸ’–This JSX element looks exactly like HTML!



JSX elements and their surroundings

πŸ’–JSX elements are treated as JavaScript expressions

 πŸ’–They can go anywhere that JavaScript expressions can go.

πŸ’–That means that a JSX element can be saved in a variable, passed to a  function, stored in an object or array...you name it.

πŸ’–Here's an example of a JSX element being saved in a variable:

   const navBar = <nav>I am a nav bar</nav>;

Attributes in JSX 

πŸ’–A JSX attribute is written using HTML-like syntax: a name, followed by an equals sign, followed by a value.

πŸ’–The value should be wrapped in quotes, like this
my-attribute-name="my-attribute-value"

27/07/2017

Building web app using react.js, express.js,         node.js and mongodb

Implementing REST endpoints


school.js



var mongoose = require("mongoose");
var schoolSchema = mongoose.Schema({
    name: String,
    tagline: String
});

module.exports = mongoose.model("school", schoolSchema);
 
 
 
schoolController.js
 
 
var mongoose = require("mongoose");
var School = require("../data/school");
var _ = require("underscore");

var router = require("express").Router();
router.route("/schools/:id?").get(getSchools).post(addSchool).delete(deleteSchool);

function getSchools(req, res) {
    School.find(function (err, schools) {
        if (err)
            res.send(err);
        else
            res.json(schools);
    });
}

function addSchool(req, res) {
    var school = new School(_.extend({}, req.body));
    school.save(function (err) {
        if (err)
            res.send(err);
        else
            res.json(school);
    });
}

function deleteSchool(req, res) {
    var id = req.params.id;
    School.remove({ _id: id }, function (err, removed) {
        if (err)
            res.send(err)
        else
            res.json(removed);
    });
}

module.exports = router;
 
 
 
server.js
 
 
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var path = require("path");

var schoolController = require("./controllers/schoolController");

//Express request pipeline
var app = express();
app.use(express.static(path.join(__dirname, "../app/dist")));
app.use(bodyParser.json())
app.use("/api", schoolController);

app.listen(7777, function () {
    console.log("Started listening on port", 7777);
});

// Connect to mongodb database
mongoose.connect("mongodb://localhost/schoolfinder");
 
 
 
 

Plugging REST to react

schoolService.js

var $ = require("jquery");
var promise = require("es6-promise");
var resourceUrl = "http://localhost:7777/api/schools";

module.exports = {
    addSchool: function (school) {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl,
                data: JSON.stringify(school),
                method: "POST",
                dataType: "json",
                contentType: "application/json",
                success: resolve,
                error: reject
            });
        });
    },
    getSchools: function () {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl,
                method: "GET",
                dataType: "json",
                success: resolve,
                error: reject
            });
        });
    },
    deleteSchool: function (school) {
        var Promise = promise.Promise;
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: resourceUrl + "/" + school._id,
                method: "DELETE",
                dataType: "json",
                success: resolve,
                error: reject
            });
        });
    }
}
 
 
 
 
schoolsStore.js
 
 
var dispatcher = require("../dispatcher");
var schoolService = require("../services/schoolService");

function SchoolStore() {
    var listeners = [];

    function onChange(listener) {
        getSchools(listener);
        listeners.push(listener);
    }
    
    function getSchools(cb){
        schoolService.getSchools().then(function (res) {
            cb(res);
        });
    }

    function addSchool(school) {
    schoolService.addSchool(school).then(function (res) {
            console.log(res);
            triggerListeners();
        });
    }

    function deleteSchool(school) {
   schoolService.deleteSchool(school).then(function (res) {
            console.log(res);
            triggerListeners();
        });
    }

    function triggerListeners() {
        getSchools(function (res) {
            listeners.forEach(function (listener) {
                listener(res);
            });
        });
    }

    dispatcher.register(function (payload) {
        var split = payload.type.split(":");
        if (split[0] === "school") {
            switch (split[1]) {
                case "addSchool":
                    addSchool(payload.school);
                    break;
                case "deleteSchool":
                    deleteSchool(payload.school);
                    break;
            }
        }
    });

    return {
        onChange: onChange
    }
}

module.exports = SchoolStore();
 
 
 
 
main.jsx

var React = require("react");
var ReactDOM = require("react-dom");
var SchoolsList = require("./components/SchoolsList.jsx");
var schoolsStore = require("./stores/schoolsStore");
var _schools = [];
var getSchoolsCallback = function(schools){
    _schools = schools;
    render();
};
schoolsStore.onChange(getSchoolsCallback);

function render(){
ReactDOM.render(<SchoolsList schools={_schools} />, document.getElementById("container"));    
}





 

 

 

 

 
 
 

 

Tuesday, August 1, 2017

26/07/2017

Building web app using react.js, express.js, node.js and mongodb

SchoolInfo.jsx

var React = require("react");

module.exports = React.createClass({
    render:function(){
        return(
            <div className="panel panel-default">
                <div className="panel-heading">
                    {this.props.info.name}
                </div>
                <div className="panel-body">
                    {this.props.info.tagline}
                </div>
            </div>
        )
    }
})
 
 
 
 
 
SchoolsList.jsx
 
var React = require("react");
var SchoolInfo = require("./SchoolInfo.jsx")

module.exports = React.createClass({
   render:function(){
       return(
        <div className="row">
         <div className="col-md-6">

          </div>
          <div className="col-md-6">
            {
              this.props.schools.map(function(s,index){
                      return(
               <SchoolInfo info={s} key={"school"+index} />
                            )         
                        })
                    }
                </div>
           </div>
       )
   } 
});
 
 
 
 
main.jsx
 
 
var React = require("react");
var ReactDOM = require("react-dom");
var SchoolsList = require("./components/SchoolsList.jsx");
var_schools =[{name:"Lovedale",tagline:"this is a wonderful school"},
            {name:"Bishop",tagline:"Another great school"}];
                
function render(){
ReactDOM.render(<SchoolsList schools={_schools} />, document.getElementById("container"));    
}
render();
 
 
 
 

Creating a dispatcher

dispatcher.js

var Guid = require("guid");

var listeners = {};

function dispatch(payload) {
    for (var id in listeners) {
        listeners[id](payload);
    }
}

function register(cb) {
    var id = Guid.create();
    listeners[id] = cb;
}

module.exports = {
    register: register,
    dispatch: dispatch
}

 

Creating Actions Helper

SchoolActions.js

var dispatcher = require("../dispatcher");

module.exports = {
    addSchool:function(school){
        dispatcher.dispatch({
           school:school,
           type:"school:addSchool" 
        });
    },
    deleteSchool:function(school){
        dispatcher.dispatch({
           school:school,
           type:"school:deleteSchool" 
        });
    }
}
 
 
 

Creating Store

schoolsStore.js

var dispatcher = require("../dispatcher");

function SchoolStore() {
    var listeners = [];
    var schools = [{ name: "Lovedale", tagline:"A wonderful school" }, 
                    { name: "Bishop",tagline:"An awesome school" }, 
                    { name: "Daffodils", tagline:"An excellent school" }];

    function getSchools() {
        return schools;
    }

    function onChange(listener) {
        listeners.push(listener);
    }

    function addSchool(school) {
        schools.push(school)
        triggerListeners();
    }

    function deleteSchool(school) {
        var _index;
        schools.map(function (s, index) {
            if (s.name === school.name) {
                _index = index;
            }
        });
        schools.splice(_index, 1);
        triggerListeners();
    }

    function triggerListeners() {
        listeners.forEach(function (listener) {
            listener(schools);
        });
    }

    dispatcher.register(function (payload) {
        var split = payload.type.split(":");
        if (split[0] === "school") {
            switch (split[1]) {
                case "addSchool":
                    addSchool(payload.school);
                    break;
                case "deleteSchool":
                    deleteSchool(payload.school);
                    break;
            }
        }
    });

    return {
        getSchools: getSchools,
        onChange: onChange
    }
}

module.exports = SchoolStore();
 
 
 
update "main.jsx" file
 
 
var React = require("react");
var ReactDOM = require("react-dom");
var SchoolsList = require("./components/SchoolsList.jsx");
var schoolsStore = require("./stores/schoolsStore");
var _schools = schoolsStore.getSchools();
schoolsStore.onChange(function(schools){
    _schools = schools;
    render();
});

function render(){ 
 ReactDOM.render(<SchoolsList schools={_schools} />, document.getElementById("container"));    
}

render(); 

 

Addind behavior to components

 AddSchool.jsx

var React = require("react");
var actions = require("../actions/SchoolActions");

module.exports = React.createClass({
    getInitialState:function(){
      return {
          name:"",
          tagline:""
      }  
    },
    addSchool:function(e){
        e.preventDefault();
        actions.addSchool(this.state);
    },
    handleInputChange:function(e){
      e.preventDefault();
      var name = e.target.name;
      var state = this.state;
      state[name] = e.target.value;
      this.setState(state);
    },
    render:function(){
        return(
      <form className="form" onSubmit={this.addSchool}>
     <div className="form-group">
  <label className="control-label" htmlFor="name">School Name:</label>
<input type="text" className="form-control" id="name" name="name" value={this.state.name} onChange={this.handleInputChange} placeholder="School Name" />                    
     </div>
  <div className="form-group">
 <label className="control-label" htmlFor="tagline">Tagline:</label>
<input type="text" className="form-control" id="tagline" name="tagline" value={this.state.address} onChange={this.handleInputChange} placeholder="Tagline" />                    
                </div>
                <div className="form-group">
                    <button className="btn" type="submit">Add School</button>
                </div>
            </form>
        )
    }
})

 

FLUX flow

 

update the "SchoolsList.jsx"

var React = require("react");
var SchoolInfo = require("./SchoolInfo.jsx")
var AddSchool = require("./AddSchool.jsx");

module.exports = React.createClass({
   render:function(){
       return(
           <div className="row">
                <div className="col-md-6">
                    <AddSchool />
                </div>
                <div className="col-md-6">
                    {
                        this.props.schools.map(function(s,index){
                            return(
                                <SchoolInfo info={s} key={"school"+index} />
                            )         
                        })
                    }
                </div>
           </div>
       )
   } 
});
 
 
 
update the "SchoolInfo.jsx
 
 
var React = require("react");
var actions = require("../actions/SchoolActions");

module.exports = React.createClass({
    deleteSchool: function(e){
        e.preventDefault();
        actions.deleteSchool(this.props.info);
    },
    render:function(){
        return(
            <div className="panel panel-default">
                <div className="panel-heading">
                    {this.props.info.name}
<span className="pull-right text-uppercase delete-button" onClick={this.deleteSchool}>&times;</span>
                </div>
                <div className="panel-body">{this.props.info.tagline}</div>
            </div>
        )
    }
}) 
 

 

 

  

 

 

 

 

 

 

25/07/2017

Building web app using react.js, express.js, node.js and mongodb

Backend code

var express = require("express");
var path = require("path");

var app = express();
app.use(express.static(path.join(__dirname,"../app/dist")));
app.listen(7777,function(){
    console.log("Started listening on port", 7777);
})
 
 
 
index.html
 
<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>School Finder</title>
    <link href="bootstrap.min.css" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />
</head>

<body>
    <div class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">School Finder</a>
            </div>
        </div>
    </div>
    <div id="container" class="container"></div>
    <script src="main.js"></script>
</body>

</html>
 
 
 
 
gulpfile.js
 
var gulp = require("gulp");
var browserify = require("browserify");
var reactify = require("reactify");
var source = require("vinyl-source-stream");

gulp.task("bundle", function () {
    return browserify({
        entries: "./app/main.jsx",
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source("main.js"))
        .pipe(gulp.dest("app/dist"))
});

gulp.task("copy", ["bundle"], function () {
    return gulp.src(["app/index.html","app/lib/bootstrap-css/css/bootstrap.min.css","app/style.css"])
        .pipe(gulp.dest("app/dist"));
});

gulp.task("default",["copy"],function(){
   console.log("Gulp completed..."); 
});
 
 
 
 
πŸ’–In our gulpfile we have created two tasks,
a) Task bundle, takes "main.jsx" file, which is currently empty, transpils jsx code to plain javascript using "reactify" then stream sources it using "vinyl-source-stream" further creates "main.js" file on the fly in "dist" directory with transpiled js code in it.

b) Task copy,  takes index.html, bootstrap.min.css and style.css files files and copies them to "dist" folder.
  

 
 

HTML introduction

HTML stands for Hyper Text Markup Language. HTML describes the structure of web page using markup. HTML elements are the building blo...