├── .gitignore
├── src
├── views
│ ├── index.ejs
│ ├── layout.ejs
│ └── contact.ejs
├── server.js
├── routes.js
└── public
│ └── style.css
├── package.json
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 |
--------------------------------------------------------------------------------
/src/views/index.ejs:
--------------------------------------------------------------------------------
1 | <% if (messages.success) { %>
2 |
<%= messages.success %>
3 | <% } %>
4 |
5 | Working With Forms in Node.js
6 |
--------------------------------------------------------------------------------
/src/views/layout.ejs:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Forms in Node.js
6 |
7 |
8 |
9 | <%- body %>
10 |
11 |
12 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "node-forms",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "src/server.js",
6 | "scripts": {
7 | "start": "nodemon src/server.js"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cookie-parser": "^1.4.4",
14 | "csurf": "^1.10.0",
15 | "ejs": "^3.0.1",
16 | "express": "^4.17.1",
17 | "express-flash": "^0.0.2",
18 | "express-layout": "^0.1.0",
19 | "express-session": "^1.17.0",
20 | "express-validator": "^6.3.1",
21 | "helmet": "^3.21.2",
22 | "multer": "^1.4.2"
23 | },
24 | "devDependencies": {
25 | "nodemon": "^2.0.2"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/server.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const express = require('express');
3 | const layout = require('express-layout');
4 | const bodyParser = require('body-parser');
5 | const cookieParser = require('cookie-parser');
6 | const session = require('express-session');
7 | const flash = require('express-flash');
8 | const helmet = require('helmet');
9 |
10 | const routes = require('./routes');
11 | const app = express();
12 |
13 | app.set('views', path.join(__dirname, 'views'));
14 | app.set('view engine', 'ejs');
15 |
16 | const middlewares = [
17 | helmet(),
18 | layout(),
19 | express.static(path.join(__dirname, 'public')),
20 | bodyParser.urlencoded({ extended: true }),
21 | cookieParser(),
22 | session({
23 | secret: 'super-secret-key',
24 | key: 'super-secret-cookie',
25 | resave: false,
26 | saveUninitialized: false,
27 | cookie: { maxAge: 60000 }
28 | }),
29 | flash(),
30 | ];
31 | app.use(middlewares);
32 |
33 | app.use('/', routes);
34 |
35 | app.use((req, res, next) => {
36 | res.status(404).send("Sorry can't find that!");
37 | });
38 |
39 | app.use((err, req, res, next) => {
40 | console.error(err.stack);
41 | res.status(500).send('Something broke!');
42 | });
43 |
44 | app.listen(3000, () => {
45 | console.log('App running at http://localhost:3000');
46 | });
47 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Creating and Handling Forms in Node.js
2 |
3 | https://www.sitepoint.com/creating-and-handling-forms-in-node-js/
4 |
5 | ## Requirements
6 |
7 | * [Node.js](http://nodejs.org/) (8.9.0+)
8 |
9 | ## Installation Steps (if applicable)
10 |
11 | 1. Clone repo
12 | 2. Run `npm install`
13 | 3. Run `npm start`
14 | 4. Visit http://localhost:3000/
15 |
16 | ## License
17 |
18 | The MIT License (MIT)
19 |
20 | Copyright (c) 2020 SitePoint
21 |
22 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
23 |
24 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
25 |
26 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 |
--------------------------------------------------------------------------------
/src/views/contact.ejs:
--------------------------------------------------------------------------------
1 |
13 |
14 |
39 |
--------------------------------------------------------------------------------
/src/routes.js:
--------------------------------------------------------------------------------
1 | const express = require('express');
2 | const router = express.Router();
3 | const { check, validationResult, matchedData } = require('express-validator');
4 |
5 | const csrf = require('csurf');
6 | const csrfProtection = csrf({ cookie: true });
7 |
8 | const multer = require('multer');
9 | const upload = multer({ storage: multer.memoryStorage() });
10 |
11 | router.get('/', (req, res) => {
12 | res.render('index');
13 | });
14 |
15 | router.get('/contact', csrfProtection, (req, res) => {
16 | res.render('contact', {
17 | data: {},
18 | errors: {},
19 | csrfToken: req.csrfToken()
20 | });
21 | });
22 |
23 | router.post('/contact', upload.single('photo'), csrfProtection, [
24 | check('message')
25 | .isLength({ min: 1 })
26 | .withMessage('Message is required')
27 | .trim(),
28 | check('email')
29 | .isEmail()
30 | .withMessage('That email doesn‘t look right')
31 | .bail()
32 | .trim()
33 | .normalizeEmail()
34 | ], (req, res) => {
35 | const errors = validationResult(req);
36 | if (!errors.isEmpty()) {
37 | return res.render('contact', {
38 | data: req.body,
39 | errors: errors.mapped(),
40 | csrfToken: req.csrfToken()
41 | });
42 | }
43 |
44 | const data = matchedData(req);
45 | console.log('Sanitized: ', data);
46 | // Homework: send sanitized data in an email or persist in a db
47 |
48 | if (req.file) {
49 | console.log('Uploaded: ', req.file);
50 | // Homework: Upload file to S3
51 | }
52 |
53 | req.flash('success', 'Thanks for the message! I‘ll be in touch :)');
54 | res.redirect('/');
55 | });
56 |
57 | module.exports = router;
58 |
--------------------------------------------------------------------------------
/src/public/style.css:
--------------------------------------------------------------------------------
1 | html {
2 | height: 100%;
3 | }
4 | body {
5 | display: flex;
6 | flex-direction: column;
7 | align-items: center;
8 | justify-content: center;
9 | min-height: 100%;
10 | margin: 0;
11 | background: #fff;
12 | font-family: -apple-system, 'Segoe UI', sans-serif;
13 | }
14 | * {
15 | box-sizing: border-box;
16 | }
17 | h2 {
18 | margin: 0 0 1em;
19 | font-size: 20px;
20 | }
21 |
22 | .form-header {
23 | width: 100%;
24 | max-width: 400px;
25 | }
26 | form {
27 | width: 100%;
28 | width: 100%;
29 | max-width: 400px;
30 | padding: 20px;
31 | background: #f8f8f8;
32 | border: 1px solid rgba(0,0,0,.1);
33 | border-color: rgba(0,0,0,.05) rgba(0,0,0,.08) rgba(0,0,0,.1);
34 | border-radius: 3px;
35 | box-shadow: 0 3px 4px rgba(0,0,0,.05);
36 | }
37 | label {
38 | display: block;
39 | padding-bottom: 3px;
40 | font-size: 12px;
41 | font-weight: bold;
42 | color: #555;
43 | text-transform: uppercase;
44 | }
45 | .input {
46 | width: 100%;
47 | margin-bottom: 5px;
48 | padding: 10px;
49 | border: 1px solid rgba(0,0,0,.1);
50 | border-radius: 3px;
51 | background: #fff;
52 | font: inherit;
53 | }
54 | .input:focus {
55 | outline: none;
56 | border-color: rgba(0,0,0,.3);
57 | }
58 | .form-field {
59 | margin-bottom: 10px;
60 | }
61 | .error, .errors-list {
62 | font-size: 14px;
63 | color: #C00;
64 | }
65 | .errors-list {
66 | margin: 0 0 1.5em;
67 | padding: 0 0 0 15px;
68 | }
69 | .form-field-invalid .input {
70 | border-color: #C00;
71 | }
72 | .form-actions {
73 | margin-top: 20px;
74 | }
75 | .btn {
76 | display: block;
77 | width: 100%;
78 | padding: 10px;
79 | background: #24b47e;
80 | border: 1px solid rgba(0,0,0,.1);
81 | border-width: 1px 1px 3px;
82 | border-radius: 3px;
83 | font: inherit;
84 | color: #fff;
85 | cursor: pointer;
86 | text-shadow: 0 1px 0 rgba(0,0,0,.3), 0 1px 1px rgba(0,0,0,.2);
87 | }
88 | .btn:hover,
89 | .btn:focus {
90 | outline: none;
91 | background: #2AA172;
92 | }
93 | .btn:active {
94 | transform: translateY(1px);
95 | }
96 | .flash {
97 | padding: 15px 20px;
98 | border: 1px solid;
99 | border-radius: 3px;
100 | }
101 | .flash-success {
102 | background-color: #d4edda;
103 | border-color: #c3e6cb;
104 | color: #155724;
105 | }
106 |
--------------------------------------------------------------------------------