For now, we have two options (methods) of sending data to the server. What are they, and how do they send their data? →
Note that POST is not any more secure than GET ….
So far… we know two ways that the user can make a browser send a request to the server: →
Let's see how form submission works. →
To create a form that sends data, you'll need to:
An HTML form
element has the following attributes:
Your form's fields have the following attributes:
To handle data in the request body, you'll need to:
body-parser
app.get
to handle requesting the original formAgain, the body of a POST is likely to be encoded and compressed, so to parse out the data and add it to the request
object, use the body-parser middleware:
const bodyParser = require('body-parser');
// only handle urlencoded data...
// extended: false specifies that incoming values will be treated as strings
// or arrays
app.use(bodyParser.urlencoded({ extended: false }));
Here's an example that takes a name entered by the user… and displays it on the page directly. In your app.js… →
(some setup)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({ extended: false }));
// this is middleware to log method and path
app.use(function(req, res, next) {
console.log(req.method, req.path);
next();
});
We'll create a global variable to store our data. Definitely not conventional; we'll use real data stores later.
// oops, a global... ok for now...
const myName = '';
app.get('/', function(req, res) {
res.render('simple-form', {'myName':myName});
});
app.post('/', function(req, res) {
console.log(req.body);
// change the global
myName = req.body.myName;
res.redirect('/');
});
app.listen(8080);
In simple-form.handlebars
Current value of "myName": {{myName}}
keeping track of cat names (from our previous demo)
a mad libs form…
a number guessing game…