Thursday, May 24, 2018

Create a simple messages service (part 4)

1- To solve for the undefined message in the console, we need to install a body parser app. So, in console, type

npm install -s body-parser

2- Once installed, let's require it at the top of our server.js file (above the call to express app):
var bodyParser = require('body-parser')
3- Set the bodyParser variable as middleware* with app.use.

Add this code below app.use(express.static(__dirname))
app.use(bodyParser.json())
*Middleware: it works as a communication layer between client and server: a request comes in and goes out through the middleware before ever hitting your own logic

4- Go back to Postman and hit "send"
5- The console should show the name and message properties for the message object

{"name": "Jane", "message": "from postman"}

6- Instead of console logging the object, we will push this object directly into the messages array:
//i.e. how to handle the post requests from client/browser
app.post('/messages', (req, res) => {
  messages.push(req.body)
  res.sendStatus(200)
})
7- Go back to Postman and hit "send"

8- Go back to localhost:3000 and hit "refresh", you will notice the name and message we sent via Postman are showing up in the list

9- Post messages from the browser and not from Postman: 

Go back to the HTML file and below the get messages function, use a post messages function:
//posts the message via browser and no longer via Postman
function postMessage(message) {
  $.post('http://localhost:3000/messages', message)
}
10- Modify the form in the HTML to also show a message field. This is to allow for sending both name and message data:
  <div class="jumbotron">
    <h1 class="display-4">
      Send message
    </h1>
    <br>
    <input id="name" class="form-control" placeholder="Name">
    <br>
    <textarea id="message" class="form-control" placeholder="Message"></textarea>
    <br>
    <button id="send" class="btn btn-success">Send</button>
  </div>
11- Modify the click() event by creating a message variable and assigning the values from the input fields into it (with the help of jQuery's val() function):
$(()=>{
  $('#send').click(()=>{
    var message = { name: $('#name').val(), message: $('#message').val() }
    postMessage(message)
  })
  getMessages()
})
12- Refresh the page in the browser. Add text to both input fields and hit "send", then refresh the page. Now, below the form, two "undefined" messages will show up. This is because this data is being sent to the server in URL format (URL encoded). So we must set up body parser app to support this. 

Below the app.use(bodyParser.json()) call, let's add:
app.use(bodyParser.urlencoded({extended: false}))
13- Refresh the page in the browser. Add text to both input fields and hit "send", then refresh the page. Now, the text you just added should show up below the fields.

Please remember: in server.js we hold the code that instructs the server how to handle the data that's being transmitted with the client/browser.

To sum up. Here, we:
  1. Required and used the body parser app to interpret JSON formatted data
  2. Tested this via Postman app
  3. On the front end, we used jQuery's $.get() function to get the contents from the message variable in JSON format
  4. On the front end, we also used jQuery's $.post() function to post the contents from the input fields over to the message variable in JSON format which is located in the /messages address
  5. Used body parser app to interpret URL encoded data that came from the client side

Tuesday, May 22, 2018

Create a simple messages service (part 3: testing the POST service via Postman app)

1- We begin by making sure our post function is working properly. To do this, we add a post function below our get function from our "express" web app variable:
app.post('/messages', (req,res) => {
  console.log(req.body)
  res.sendStatus(200)
})

2- Make sure nodemon is still running

3- Let's download Postman app to test the post functionality. Then install in the system.

4- Open Postman and choose "Post" from the address dropdown
5- In the request URL field, add your post end point address localhost:3000/messages

6- Go to the Body tab and select JSON from the dropdown

7- Then, in the body area, we add our message object:
{"name": "Jane", "message": "from postman"}

Wednesday, May 16, 2018

Create a simple messages service (part 2)

1- You can use app.get() to to show custom results to specific urls. For testing purposes, add the following inside the server.js file, after the app.use() function:

app.get('/messages', (req, res) => {
res.send('hello')
})

Where:
  • req: element that holds the data
  • res: action to take once connection with data is established

2- In your browser, go to: http://localhost:3000/messages

You will notice the url shows the message hello

 3- Now, let's create a variable called messages and add data into it
var messages = [
{name: 'Tim', message: 'Hi'},
{name: 'John', message: 'Hello'}
]
4- Select this variable as data to be sent to the messages url by modifying the app.get() parameters
//i.e. how to handle the post requests from client/browser
app.get('/messages', (req, res) => {
res.send(messages)
})
5- In the index.html file, modify this line:

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

Wednesday, May 9, 2018

How to setup express.js and execute server to display static content

1- Create a server.js file
2- In console, install node
npm init --yes
3- In console, install express framework
npm install -s express
where -s indicates this should be registered as a dependency
4- Next, go back to the empty server.js file and create the express library variable
var express = require('express')
5- Now, create the variable for the express object
var app = express()
6- Now, add the code that will turn on the server upon execution of the app
app.listen(3000)
and run in the console: nodemon ./server.js
7-  In your browser, head to http://localhost:3000/ this will give you a 404 error in the console (see network tab). This is because no data was sent to the server
8- For example purposes, in the same dir, let's create an index.html file and add the text/string:
hello
9- Back in server.js, instruct the app to read static files from the same directory
app.use(express.static(__dirname))
10- Now, let's adjust the app.listen(3000) event to include the html to be delivered by the server:
var server = app.listen(3000, () => {console.log('server is listening on port', server.address().port)})

In simple terms, here, you:
  1. Installed node and express framework dependencies
  2. Called express library and object
  3. Server needs to display data, because of this, create the content to be displayed
  4. Instruct the app where to read the data from
  5. Instruct the app to execute server
  6. Server displays the data

Monday, May 7, 2018

How to write to a json file

1- Call the filesystem
var fs = require('fs')
2- Define the object to be added to the JSON file
var data = {
  name: "rafael"
}
3- Use filesystem's writeFile() function to write into a custom "data.json" file
fs.writeFile("./data.json", JSON.stringify(data), (err) => {
  console.log("write successful", err)
})
Where: JSON.stringify function saves the data as a string

That's it!

Friday, April 27, 2018

How to read directories

1- Invoke the filesystem

var fs = require('fs')

2- Use the function readdir() from the fs variable

fs.readdir('c:/', (err, data) => {
 console.log(data) 
})

3- You will get a list of contents and directories within your C: drive

 [ '$GetCurrent',
  '$RECYCLE.BIN',
  'Documents and Settings',
  'Program Files',
  'Program Files (x86)',
  'ProgramData',
  'Users',
  'wamp64',
  'Windows',
  'Windows10Upgrade' ]