From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../server-side/express_nodejs/forms/index.html | 276 +++++++++++++++++++++ .../ms/learn/server-side/express_nodejs/index.html | 77 ++++++ files/ms/learn/server-side/index.html | 59 +++++ 3 files changed, 412 insertions(+) create mode 100644 files/ms/learn/server-side/express_nodejs/forms/index.html create mode 100644 files/ms/learn/server-side/express_nodejs/index.html create mode 100644 files/ms/learn/server-side/index.html (limited to 'files/ms/learn/server-side') diff --git a/files/ms/learn/server-side/express_nodejs/forms/index.html b/files/ms/learn/server-side/express_nodejs/forms/index.html new file mode 100644 index 0000000000..6e50f7b27a --- /dev/null +++ b/files/ms/learn/server-side/express_nodejs/forms/index.html @@ -0,0 +1,276 @@ +--- +title: 'Express Tutorial Part 6: Working with forms' +slug: Learn/Server-side/Express_Nodejs/forms +tags: + - Beginner + - CodingScripting + - Express + - Forms + - HTML forms + - Learn + - NeedsTranslation + - Node + - TopicStub + - server-side +translation_of: Learn/Server-side/Express_Nodejs/forms +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}
+ +

In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.

+ + + + + + + + + + + + +
Prerequisites:Complete all previous tutorial topics, including Express Tutorial Part 5: Displaying library data
Objective:To understand how write forms to get data from users, and update the database with this data.
+ +

Overview

+ +

An HTML Form is a group of one or more fields/widgets on a web page that can be used to collect information from users for submission to a server. Forms are a flexible mechanism for collecting user input because there are suitable form inputs available for entering many different types of data—text boxes, checkboxes, radio buttons, date pickers, etc. Forms are also a relatively secure way of sharing data with the server, as they allow us to send data in POST requests with cross-site request forgery protection.

+ +

Working with forms can be complicated! Developers need to write HTML for the form, validate and properly sanitize entered data on the server (and possibly also in the browser), repost the form with error messages to inform users of any invalid fields, handle the data when it has successfully been submitted, and finally respond to the user in some way to indicate success.

+ +

In this tutorial we're going to show you how the above operations may be performed in Express. Along the way we'll extend the LocalLibrary website to allow users to create, edit and delete items from the library.

+ +
+

Note: We haven't looked at how to restrict particular routes to authenticated or authorised users, so at this point any user will be able to make changes to the database.

+
+ +

HTML Forms

+ +

First a brief overview of HTML Forms. Consider a simple HTML form, with a single text field for entering the name of some "team", and its associated label:

+ +

Simple name field example in HTML form

+ +

The form is defined in HTML as a collection of elements inside <form>...</form> tags, containing at least one input element of type="submit".

+ +
<form action="/team_name_url/" method="post">
+    <label for="team_name">Enter name: </label>
+    <input id="team_name" type="text" name="name_field" value="Default name for team.">
+    <input type="submit" value="OK">
+</form>
+ +

While here we have included just one (text) field for entering the team name, a form may contain any number of other input elements and their associated labels. The field's type attribute defines what sort of widget will be displayed. The name and id of the field are used to identify the field in JavaScript/CSS/HTML, while value defines the initial value for the field when it is first displayed. The matching team label is specified using the label tag (see "Enter name" above), with a for field containing the id value of the associated input.

+ +

The submit input will be displayed as a button (by default)—this can be pressed by the user to upload the data contained by the other input elements to the server (in this case, just the team_name). The form attributes define the HTTP method used to send the data and the destination of the data on the server (action):

+ + + +

Form handling process

+ +

Form handling uses all of the same techniques that we learned for displaying information about our models: the route sends our request to a controller function which performs any database actions required, including reading data from the models, then generates and returns an HTML page. What makes things more complicated is that the server also needs to be able to process data provided by the user, and redisplay the form with error information if there are any problems.

+ +

A process flowchart for processing form requests is shown below, starting with a request for a page containing a form (shown in green):

+ +

As shown in the diagram above, the main things that form handling code needs to do are are:

+ +
    +
  1. Display the default form the first time it is requested by the user. +
      +
    • The form may contain blank fields (e.g. if you're creating a new record), or it may be pre-populated with initial values (e.g. if you are changing a record, or have useful default initial values).
    • +
    +
  2. +
  3. Receive data submitted by the user, usually in an HTTP POST request.
  4. +
  5. Validate and sanitize the data.
  6. +
  7. If any data is invalid, re-display the form—this time with any user populated values and error messages for the problem fields.
  8. +
  9. If all data is valid, perform required actions (e.g. save the data in the database, send a notification email, return the result of a search, upload a file, etc.)
  10. +
  11. Once all actions are complete, redirect the user to another page.
  12. +
+ +

Often form handling code is implemented using a GET route for the initial display of the form and a POST route to the same path for handling validation and processing of form data. This is the approach that will be used in this tutorial!

+ +

Express itself doesn't provide any specific support for form handling operations, but it can use middleware to process POST and GET parameters from the form, and to validate/sanitize their values.

+ +

Validation and sanitization

+ +

Before the data from a form is stored it must be validated and sanitized:

+ + + +

For this tutorial we'll be using the popular express-validator module to perform both validation and sanitization of our form data.

+ +

Installation

+ +

Install the module by running the following command in the root of the project.

+ +
npm install express-validator --save
+
+ +

Using express-validator

+ +
+

Note: The express-validator guide on  Github provides a good overview of API. We recommend you read that to get an idea of all its capabilities (including creating custom validators). Below we cover just a subset that is useful for the LocalLibrary.

+
+ +

To use the validator in our controllers we have to require the functions we want to use from the 'express-validator/check' and 'express-validator/filter' modules, as shown below:

+ +
const { body,validationResult } = require('express-validator/check');
+const { sanitizeBody } = require('express-validator/filter');
+
+ +

There are many functions available, allowing you to check and sanitize data from request parameters, body, headers, cookies, etc., or all of them at once. For this tutorial, we'll primarily be using bodysanitizeBody, and validationResult (as "required" above).

+ +

The functions are defined as below:

+ + + +

The validation and sanitization chains are middleware that should be passed to the Express route handler (we do this indirectly, via the controller). When the middleware runs, each validator/sanitizer is run in the order specified.

+ +

We'll cover some real examples when we implement the LocalLibrary forms below.

+ +

Form design

+ +

Many of the models in the library are related/dependent—for example, a Book requires an Author, and may also have one or more Genres. This raises the question of how we should handle the case where a user wishes to:

+ + + +

For this project we will simplify the implementation by stating that a form can only:

+ + + +
+

Note: A more "robust" implementation might allow you to create the dependent objects when creating a new object, and delete any object at any time (for example, by deleting dependent objects, or by removing references to the deleted object from the database).

+
+ +

Routes

+ +

In order to implement our form handling code we will need two routes that have the same URL pattern. The first (GET) route is used to display a new empty form for creating the object. The second route (POST) is used for validating data entered by the user, and then saving the information and redirecting to the detail page (if the data is valid) or redisplaying the form with errors (if the data is invalid).

+ +

We have already created the routes for all our model's create pages in /routes/catalog.js (in a previous tutorial). For example, the genre routes are shown below:

+ +
// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id).
+router.get('/genre/create', genre_controller.genre_create_get);
+
+// POST request for creating Genre.
+router.post('/genre/create', genre_controller.genre_create_post);
+
+ +

Express forms subarticles

+ +

The following subarticles will take us through the process of adding the required forms to out example application. You need to read and work through each one in turn, before moving on to the next one.

+ +
    +
  1. Create Genre form — Defining our page to create Genre objects.
  2. +
  3. Create Author form — Defining a page for creating Author objects.
  4. +
  5. Create Book form — Defining a page/form to create Book objects.
  6. +
  7. Create BookInstance form — Defining a page/form to create BookInstance objects.
  8. +
  9. Delete Author form — Defining a page to delete Author objects.
  10. +
  11. Update Book form — Defining  page to update Book objects.
  12. +
+ +

Challenge yourself

+ +

Implement the delete pages for the Book, BookInstance, and Genre models, linking them from the associated detail pages in the same way as our Author delete page. The pages should follow the same design approach:

+ + + +

A few tips:

+ + + +

Implement the update pages for the BookInstance, Author, and Genre models, linking them from the associated detail pages in the same way as our Book update page.

+ +

A few tips:

+ + + +

Summary

+ +

Express, node, and third party packages on NPM provide everything you need to add forms to your website. In this article you've learned how to create forms using Pug, validate and sanitize input using express-validator, and add, delete, and modify records in the database.

+ +

You should now understand how to add basic forms and form-handling code to your own node websites!

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}

+ +

In this module

+ + + +

 

diff --git a/files/ms/learn/server-side/express_nodejs/index.html b/files/ms/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..968f3e40e2 --- /dev/null +++ b/files/ms/learn/server-side/express_nodejs/index.html @@ -0,0 +1,77 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +tags: + - Beginner + - CodingScripting + - Express + - Express.js + - Intro + - JavaScript + - Learn + - NeedsTranslation + - Node + - Server-side programming + - TopicStub + - node.js +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express is a popular unopinionated web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.

+ +

Prerequisites

+ +

Before starting this module you will need to understand what server-side web programming and web frameworks are, ideally by reading the topics in our Server-side website programming first steps module. A general knowledge of programming concepts and JavaScript is highly recommended, but not essential to understanding the core concepts.

+ +
+

Note: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

+ +

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

+
+ +

Guides

+ +
+
Express/Node introduction
+
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
+
Setting up a Node (Express) development environment
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Express Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Express Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Express Tutorial Part 3: Using a Database (with Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Express Tutorial Part 4: Routes and controllers
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Express Tutorial Part 5: Displaying library data
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
+
Express Tutorial Part 6: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Express Tutorial Part 7: Deploying to production
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

See also

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
+
+ +

Adding more tutorials

+ +
+

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

+ + + +

And of course it would be excellent to have an assessment task!

+
diff --git a/files/ms/learn/server-side/index.html b/files/ms/learn/server-side/index.html new file mode 100644 index 0000000000..b497257371 --- /dev/null +++ b/files/ms/learn/server-side/index.html @@ -0,0 +1,59 @@ +--- +title: Server-side website programming +slug: Learn/Server-side +tags: + - Beginner + - CodingScripting + - Intro + - Landing + - Learn + - NeedsTranslation + - Server + - Server-side programming + - Topic + - TopicStub +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

The Dynamic Websites  Server-side programming topic is a series of modules that show how to create dynamic websites; websites that deliver customised information in response to HTTP requests. The modules provide a generic introduction to server-side programming, along with specific beginner-level guides on how to use the Django (Python) and Express (Node.js/JavaScript) web frameworks to create basic applications.

+ +

Most major websites use some kind of server-side technology to dynamically display different data as required. For example, imagine how many products are available on Amazon, and imagine how many posts have been written on Facebook? Displaying all of these using completely different static pages would be completely inefficient, so instead such sites display static templates (built using HTML, CSS, and JavaScript), and then dynamically update the data displayed inside those templates when needed, e.g. when you want to view a different product on Amazon.

+ +

In the modern world of web development, learning about server-side development is highly recommended.

+ +

Learning pathway

+ +

Getting started with server-side programming is usually easier than with client-side development, because dynamic websites tend to perform a lot of very similar operations (retrieving data from a database and displaying it in a page, validating user-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy.

+ +

A basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Similarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end".

+ +

You will need to understand "how the web works". We recommend that you first read the following topics:

+ + + +

With that basic understanding you'll be ready to work your way through the modules in this section. 

+ +

Modules

+ +

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

+ +
+
Server-side website programming first steps
+
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
+
Django Web Framework (Python)
+
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
+
Express Web Framework (Node.js/JavaScript)
+
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
+
+ +

See also

+ +
+
Node server without framework
+
This article provides a simple static file server built with pure Node.js, for those of you not wanting to use a framework.
+
-- cgit v1.2.3-54-g00ecf