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:


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

Into:

<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
This is because the slim version of jQuery doesn't recognize $.get parameters (used in step 6)

6- Create a function that will display the data from the messages url and add it to the index.html file (remember, addMessages() function makes sure to append the data to the div)
function getMessages(){
$.get('http://localhost:3000/messages', (data) => {
data.forEach(addMessages)
})
}
7- Call the getMessages() function below the click event actions
$(()=>{
  $('#send').click(()=>{
    addMessages({name: 'Tim', message: 'hello'})
  })
  getMessages()
})
8- In your browser, head to http://localhost:3000/ and reload

Result: data will be displayed on load

To sum up, here we:

1- Created a variable in the server.js file with static data
2- Instructed the server to send such data to the messages url
3- Created a jQuery function to display such data in the html

No comments:

Post a Comment