Wednesday, May 16, 2018

Create a simple messages service (part 1)

1- Install node and express dependencies

npm init --yes
npm install -s express

 2- Create express lib and app variables
 
var express = require('express')
var app = express()

 3- Instruct server to read from main dir and instruct server to start listening on port 3000 via the express app

app.use(express.static(__dirname))

server = app.listen(3000, () => { 
console.log('server started in port'), server.address().port) 
})

4- In main directory, create an index.html file and add (to the top of the index file):

- Doctype
- Jquery
- Bootstrap


<link crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" rel="stylesheet"></link>
<script crossorigin="anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> 

5- Add a simple text and button inputs by using default bootstrap classes:
<div class="container">
  <br>
  <div class="jumbotron">
    <h1 class="display-4">
      Send message
    </h1>
    <br>
    <input class="form-control" placeholder="Name">
    <br>
    <button id="send" class="btn btn-success">Send</button>
  </div>
  <div id="messages">

  </div>
</div>

6- Add a script that will inser/append our custom message inside the "#messages" div (by using JavaScript template literal variables)
<script>
// $() shorthand for document.ready() event function
// ()=> call back function with an arrow function
// it's like saying "when doc is ready,
// run this no-param arrow function
$(()=>{
  $('#send').click(()=>{
    addMessages({name: 'Tim', message: 'hello'})
  })
})

function addMessages(message) {
  $("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message}</p>`)
}

</script>
7- Execute the js file via nodemon

nodemon .\server.js

To sum up, here, we:
  1. Loaded node and express libraries in a js file
  2. Loaded bootstrap and jquery into an index.html file
  3. Instructed server actions via js file
  4. Inside the html file, created a function that inserts html + variables
  5. Inside the html file, we specified the action to take upon button click (use variables and append them to the html)
  6. Initialized server on port 3000

Result: string variables are added each time you click the send button

No comments:

Post a Comment