Forms - abbernie/web-dev-sp17 GitHub Wiki

GET

Forms using the GET method can be used to create query strings. When a form uses the method GET, the content will show up in the URL.

<form method="GET" action="/somepage">
    <input type="text" name="name" value="Your Name">
    <input type="text" name="city" value="Your City">
    <input type="submit" name="submit" value="Submit">
</form>

When the form above is submitted, the browser will go to the URL set in the "action" attribute and tacks on the form values in the query string. When submitted with the values "Jane" and "Brooklyn", this form would go to the url whateversite.com/somepage?name=Jane&city=Brooklyn&submit=Submit.

In Express, the parameters in a query string are available in the request object (or req as named in the function below). The request object has a property called query, which will contain the names of the parameters in the query string. For example:

// url is http://yourdomain/something?name=Jane&city=Brooklyn&submit=Submit (for example)
app.get('/something', function(req, res){
    var message = "Meet " + req.query.name + " from " + req.query.city
    res.send('id: ' + req.query.id);
});

POST

If we change the form method to POST in the HTML, the content is sent in a manner that we can't see in the URL. You would use this method for information that shouldn't be submitted more than once (such as entering a comment) or that shouldn't be visible in the URL, like a password. The POST method is more common than GET for use in forms.

<form method="POST" action="/process">
    <input type="text" name="name" value="Your Name">
    <input type="text" name="city" value="Your City">
    <input type="submit" name="submit" value="Submit">
</form>

In Express, instead of using app.get(), we'll use app.post(), because we're now sending data with a different http method.

The post parameters also come in through the request object in Express. This time the property of the request object is body, and just like with query, it ends with the name of the parameter from the form.

app.post('/process', function(req, res){
    res.send('Name: ' + req.body.name + ' City: ' + req.body.city ); 
});
⚠️ **GitHub.com Fallback** ⚠️