Top Banner
Interactive Web Application
32

Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Aug 13, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Interactive Web Application

Page 2: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

This lesson builds on previous lessons

With this lesson we will be picking up right where we left off from our Node.js Hosting lesson. The presentation can be found at http://rockymountaincoding.org. You can also use this direct link.

For a quick catch up (not recommended) the full example code can be downloaded here, and you can do the AppFog setup and deployment detailed on slides 34 through 46 of the presentation.

We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well.

Page 3: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

So far we've created and deployed a website with multiple routes that serves up HTML, CSS, and images

This website will be the same for every person that visits it, so it can be called static. These websites are ok.

True web applications accept and respond to user input. These are called interactive web sites.

Its time to make our website interactive!

Interactive websites have output that changes depending on user input

Page 4: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Instead of saying Hello, World! Lets optionally have it be able to say hello to somebody's name. One way we can do this, is with a route parameter.

Route parameters are part of a route that we are defining as being a parameter. Parameters are like variables, and hold values.

We will make it so if a user goes to the route /hello/name we will say hello to whatever is in the name place.

Express uses colons to indicate a part of a route is actually a parameter, whose name follows the colon. So we have a route /hello/:name, then whatever comes after /hello/ in the URL will be stored in the "name" parameter.

Let's add this route now to our server.js file right after our default empty route.

app.get('/', function(req, res) {res.render('hello');

});

app.get('/hello/:name', function(req, res) { //TODO: handle this route});

Information can be sent in the route as parameters

Page 5: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

app.get('/hello/:name', function(req, res) { var name = req.param('name'); console.log('Name sent to server: '+name);});

Now that we have this route parameter, we need to use it! We can do use using the param() function. The first argument can be the name of the route parameter we want, and it will return its value!

For now, we will use it to set a variable and output it to the console.

Restart the server

$ node server.js

And in a browser navigate to that route and put in your name, such as http://localhost:1337/hello/Aaron. While nothing will happen in the browser (we are not sending back a response or rendering anything yet) you should see the name output in the console!

$ Name sent to server: Aaron

Instead of just the console, lets also send this variable to the view!

Page 6: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

app.get('/hello/:name', function(req, res) { var name = req.param('name'); console.log('Name sent to server: '+name); res.render('hello', {name: name});});

Let's reuse some code we've written and have our server render hello.ejs for the new hello route. But we'll add another parameter in our call to render which is an object of the variables we will send to the view. To keep things simple we'll keep the name of variable the same in the view as it is in our server.

We also need to modify our view to use this variable. In EJS you can output the value of a variable by putting its name between "<%=" and "%>", for example "<%= name %>" will become the value of the name variable when rendered.

Let's modify hello.ejs to use this instead of always showing "World".

EJS templates can use variables when rendering view files

<h1> Hello, World! Hello, <%= name %>!</h1>

Page 7: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Now once again we made a change to our server file, so we need to restart our server.

And lets try out our route again--this time we should also see results in the browser!Let's see what happens when I go to http://localhost:1337/hello/Aaron now.

EJS templates can use variables when rendering view files

$ node server.js

Look at that! My name was passed from the route to the view, and displayed!

Page 8: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

While this new route works great, we modified the same view used by the default empty route. Let's see if it still works by navigating to http://localhost:1337/.

Woah looks like something went wrong! An error message was sent back instead of our view. You will also notice the error message in the console as well.

Usually error messages give hints as to what the problem is. Here it points at the "Hello, <%= name %>!" line of code in our view, and also includes the message "name is not defined".

Basically our view was expecting a variable called name, but since our empty route doesn't pass it a value for that variable, it gets very upset.

Page 9: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Save and restart the server

app.get('/', function(req, res) { res.render('hello'); res.redirect('/hello/World');});

Let's modify our empty route to simply redirect to the new hello route, which provides the view the variables. We'll use this by calling the redirect() function. Go ahead and make the following change to the empty route in server.js .

$ node server.js

Navigate to http://localhost:1337/ and see how it now redirects to http://localhost:1337/hello/World

Page 10: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website
Page 11: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

In the above example URL for mydomain.com, they are going to the route /this/is/myroute. Then there are two query parameters. firstParam with a value of "1", and secondParam with a value of "two".

URL query parameters are another way to send information to the server

http://mydomain.com/this/is/my/route?firstParam=1&secondParam=two

Domain Route Query Parameters

Another way to send information to the server can be including what are known as query parameters after the route. Basically in the URL, once the route is over, you can put a question mark and then any number of parameter name and value pairs.

Each pair separates the name and value with an equals sign, and the pairs themselves are separated with an ampersand.

Page 12: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Query parameters can be retrieved and treated just like route parameters

These parameters can be retrieved and then treated just like route parameters. Just like we used the param() function for the route parameter, it can get the query parameter.

One thing we didn't mention about the param() function is that it has an optional second argument, which is the value to use if the parameter doesn't exist. This can be very handy.

Let's modify our empty route to look for the firstName and lastName parameters, and use these in the redirect.

app.get('/', function(req, res) { var firstName = req.param('firstName', 'Mystery'); var lastName = req.param('lastName', 'Person'); res.redirect('/hello/World'); res.redirect('/hello/'+firstName+' '+lastName);});

Here we are saying look for the query parameter firstName, but if it doesn't exist use "Mystery". Then look for the query parameter lastName, but if that doesn't exist use Person. Then combine them and redirect using the result as the name route parameter for the hello route.

Page 13: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Let's try using the parameters. First we need to save and restart the server.

Here we say the values of the query parameters being used. Let's see what happens if we leave some of them off.

Now go ahead and use your name for the appropriate parameter values. For example, in the web browser navigate to http://localhost:133/?firstName=Aaron&LastName=Silverman

$ node server.js

Page 14: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Now lets test out our default parameters. Go ahead and use a URL that is missing a parameter. For example, we could remove the firstName parameter and try http://localhost:133/?LastName=Silverman

There we see one of our defaults being used. Lets try with no query parameters and we should see both defaults used.

Page 15: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website
Page 16: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Forms are a way to structure and send parameters

While query parameters get the job done, it sure is a pain for users to type them up there in the address bar. One way to make things easier for people who use your website is to leverage an HTML form.

HTML forms have different fields, such as a text box. These fields can be given names and the form can be setup to submit the names and values as query parameters.

Remember our silly sentence generator from the second lesson? It took as input a name and a place, and then combined that with some random words to generate a silly sentence.

Let's make this a web application instead of a command line program!

First we'll need a new page for our form, so lets make a new file in our views folder called sentenceinput.ejs .

Page 17: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

We'll cheat a bit here and use very simple HTML without the doctype, html, head, and body tags. This is so we can learn about forms faster--don't actually write forms this way. I highly recommend using twitter bootstrap and its forms.

Let's write code in sentenceinput.ejs with a simple HTML form that takes the name and place:

<form> Name: <input name="name" type="text" /> <br /> Place: <input name="place" type="text" /> <br /> <button type="submit">Submit</button></form>

In our server.js we'll want to add a new route for this form view. We can add it after the /bye route:

app.get('/bye', function(req, res) {res.render('bye');

});

app.get('/sentenceinput', function(req, res) {res.render('sentenceinput');

});

Page 18: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

We can then navigate to our new route and see our form at http://localhost:1337/sentenceinput

$ node server.js

Now make sure both files are saved and restart your server.

What a great little form! Lets quickly dive into what we did there.

Page 19: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

<form> </form>

The HTML form tag groups all of its content into one form. This is useful as when the form is submitted, it automatically knows all of the relevant inputs to submit. We'll come back to this one.

Name: <input name="name" type="text" /> <br />

This is just like the name input, except here we will associate this input with a parameter named "place" instead.

Place: <input name="place" type="text" /> <br />

One type of input forms use are text boxes. These are created using an input tag with a type attribute whose value is "text". We also set a name attribute, this will be the name of the parameter associated with the input. In this case, coincidentally, name.

Lastly we use a br (break) tag so the next input is on the next line.

<button type="submit">Submit</button>

The HTML button tag creates a button whose text is the contents of the tag. By setting the type attribute to be "submit", we are telling HTML that this button should submit the form its in.

Page 20: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Go ahead and fill in some values

Then click the Submit button and see what happens

Not a whole lot. But check out the address bar! The browser actually navigated back to the page you were on, but with the values you entered now as query parameters.

Page 21: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

We can change where the form sends its values using the action attribute. Lets add that into our form.

<form action="/sentenceoutput">

Since we modified a view, and left our server code alone, we don't have to restart the server. Refresh http://localhost:1337/sentenceinput so our new changes take effect.

Then fill in some values

And submit the form!

Page 22: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

If you look at the URL, submitting the form sent the browser to the /sentenceoutput route--which is what we entered as the value for the action attribute for the form.

Following the route, we can see the query parameters whose values are what we entered.

Since the /sentenceoutput route isn't defined, our server processed it using the catch-all route. Let's make an actual route for it in our server.js file.

We'll add our /sentenceoutput route right after the /sentenceinput route, and leave ourselves TODO comments for what we want that route to do.

A form's action attribute tells it what route to submit the input values

app.get('/sentenceinput', function(req, res) { res.render('sentenceinput');});

app.get('/sentenceoutput', function(req, res) { // TODO: process query params // TODO: generate random sentence parts // TODO: send random sentence to view});

Page 23: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

First, lets go ahead and pate in some of our sentence generator code we wrote in the earlier lesson. You could also copy it from here.

app.get('/sentenceoutput', function(req, res) { var name = process.argv[2]; var place = process.argv[3];

function randomWord(wordArray) { var randomDecimal = Math.random(); var numWords = wordArray.length; var randomIndex = Math.floor(randomDecimal * numWords);

return wordArray[randomIndex]; }

var randomVerb = randomWord(verbs); var randomAdjective = randomWord(adjectives); var randomPluralNoun = randomWord(pluralNouns);});

Page 24: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Unlike earlier, we don't want to get the name and place from the command line, but rather from the values sent from the forms as query parameters. So lets change them to use the param() function.

app.get('/sentenceoutput', function(req, res) { var name = process.argv[2]; var name = req.param('name'); var place = process.argv[3]; var place = req.param('place');

Now at the end lets start by just outputting our variables to the console:

var randomVerb = randomWord(verbs); var randomAdjective = randomWord(adjectives); var randomPluralNoun = randomWord(pluralNouns);

console.log('Name: '+name); console.log('Place: '+place); console.log('Verb: '+randomVerb); console.log('Adjective: '+randomAdjective); console.log('Noun: '+randomPluralNoun);});

Page 25: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Since we modified our server, we need to restart it.

$ node server.js

Go back and reload http://localhost:1337/sentenceinput and enter some values and submit the form

Since we don't have our server render any views yet, you won't see anything happen in the browser. But we do have our console log things so go check the console and see!

Name: Curious GeorgePlace: ZooVerb: tossAdjective: heavyNoun: trees

There are our values!

Page 26: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Since our users cannot see the console, its time to make a view! We'll make one that builds a silly sentence using those five variables: name, place, verb, adjective, and noun.

Let's start by adding to the views folder a new file called sentenceoutput.ejs .

We'll be lazy again with the HTML for now and skip the doctype, html, head, and body elements. But once again that is only because this is a simple example!

Go ahead and write a sentence putting the EJS view variables where they should be. We can make bold, or strong, the words provided from the form and emphasize the words that were randomly generated using <strong> and <em> tags respectively.

<strong><%= name %></strong>likes to <em><%= verb %></em> <em><%=adjective %></em> <em/><%= noun %> </em>at the <strong><%= place %></strong>

Here we did some funny things with the spacing to make this easier to read. But remember HTML ignores spaces and new lines so this sentence will all be on one line.

Page 27: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Now that we have our view expecting these variables, lets have our route render the view with these variables. So back in server.js we'll add more after our log statements.

First, to make the code easier to read, we'll create an object to hold all the view variable name and values. Then we will call render and pass that object as the view variable argument.

console.log('Name: '+name); console.log('Place: '+place); console.log('Verb: '+randomVerb); console.log('Adjective: '+randomAdjective); console.log('Noun: '+randomPluralNoun);

var viewVars = { name: name, place: place, verb: randomVerb, adjective: randomAdjective, noun: randomPluralNoun };

res.render('sentenceoutput', viewVars);});

Page 28: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Be sure both the view file and the server file is saved. Once again, since we made a change to our server, lets restart it.

$ node server.js

Go back and reload http://localhost:1337/sentenceinput and enter some values and submit the form

This time you should see your sentence generated!

Page 29: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website
Page 30: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

I think our sentence generator is so cool that we should link to it from our hello page. Lets modify hello.ejs and add a link.

<p> <img class="cool" src="/images/icecream.jpg" /> <br /> <a href="/bye">Say Goodbye</a> </p> <p> Would you like to <a href="/sentenceinput">generate a silly sentence?</a> </p> </body>

Since we only modified a view, no need to restart the server. Now lets check out our site again. Navigate to http://localhost:1337

And now we have the link on the bottom of our page!

Page 31: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

Time to share our sentence generator with the world! Quit the server to get back to a command prompt, and lets use the AppFog command line tool to deploy our latest code.

Now navigate to your domain and try things out! This example uses http://myawesomewebsite.aws.af.cm

$ af update myawesomewebsiteUploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (18K): OK Push Status: OKStopping Application 'myawesomewebsite': OKStaging Application 'myawesomewebsite': OK Starting Application 'myawesomewebsite': OK

Page 32: Interactive Web Application - Amazon S3...We'll also be using code we wrote in Intro to Node.js lesson, however it is reproduced here as well. So far we've created and deployed a website

And since we left our log statements in, we can see what has been output on the server as well. This is useful for debugging if people start having problems, and cool to see just what is going on.

Now you can process user input and change the output of your views! You are equipped to build and deploy basic interactive web applications!

Go ahead and play around and try to make this sentence generator look nicer using twitter bootstrap, and then more interesting by adding in more text fields and having it do extra stuff!

$ af logs myawesomewebsite====> /logs/stdout.log <====

Running serverAccess locally at http://localhost:1337To stop server and return to command line, press ctrl+cName: Clifford the Big Red DogPlace: SupermarketVerb: killAdjective: giantNoun: socks