Validatie, Authenticate, Authorisatie & Mailing
Installeer express-validator
npm install express-validator
Installeer de dependencies
npm install
Voer de migrations uit, en laat de seeder eenmaal lopen
Vanaf nu heb je een database, met tabellen en gegevens
npx knex migrate:latest
npx knex seed:run
Start het project
npm run start:dev
Validatie, Authenticate, Authorisatie & Mailing
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
// Body parsing is built in to Express
app.use(express.json());
app.use(express.urlencoded({extended: true}));
// Deprecated since Express v4.16:
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({extended: true}));
request
response
express.
json()
express.json() zal data die wordt meegegeven vanaf de client omzetten naar json.
Validatie, Authenticate, Authorisatie & Mailing
Validatie is het controleren van een waarde of een methode op geldigheid of juistheid. Meestal wordt deze werkwijze gebruikt bij het versturen van data met behulp van een formulier.
app.get("/contact", contact);
app.post("/contact", postContact, contact);
request
response
express-
validator
postContact
page
controller
body('email').isEmail()
withMessage
om een gebruiksvriendelijke foutmeldingbody('email')
.isEmail()
.withMessage('Onjuist e-mailadres');
body('email')
.notEmpty()
.withMessage('E-mail is een verplicht veld.')
.isEmail()
.withMessage('Onjuist e-mailadres'),
bail
body('email')
.notEmpty()
.withMessage('E-mail is een verplicht veld.')
.bail()
.isEmail()
.withMessage('Onjuist e-mailadres'),
<% locals.inputs?.forEach(input => { %>
<%- include('./partials/form-input', input) %>
<% }); %>
export const contact = (req, res) => {
const inputs = [
{
name: "fullname",
label: "Volledige naam",
type: "text",
},
{
name: "email",
label: "E-mail",
type: "text",
},
{
name: "message",
label: "Bericht",
type: "textarea",
},
];
res.render("contact", {
inputs
});
}
import { body } from "express-validator";
export default [
body("fullname")
.notEmpty()
.withMessage("Volledige naam is een verplicht veld.")
.bail()
.isLength({ min: 2 })
.withMessage("Volledige naam moet minstens twee tekens bevatten."),
body("email")
.notEmpty()
.withMessage("E-mail is een verplicht veld.")
.bail()
.isEmail()
.withMessage("Onjuist e-mailadres"),
body("message")
.notEmpty()
.withMessage("Bericht is een verplicht veld.")
.bail()
.isLength({ min: 10 })
.withMessage("Bericht moet minstens tien tekens bevatten."),
];
ContactValidation
importeert in app.js
app.post("/contact", ContactValidation, postContact, contact);
export const postContact = async (req, res, next) => {
const errors = validationResult(req);
// if we have validation errors
if (!errors.isEmpty()) {
console.log("uh oh, we got errors dude");
res.send(errors);
}
};
next()
next()
functie. if (!errors.isEmpty()) {
// set the form error fields
req.formErrorFields = {};
errors.array().forEach((error) => {
req.formErrorFields[error.path] = error.msg;
});
// set the flash message
req.flash = {
type: "danger",
message: "Er zijn fouten opgetreden",
};
return next();
}
export const contact = (req, res) => {
const inputs = [
{
name: "fullname", label: "Volledige naam", type: "text",
err: req.formErrorFields?.fullname ? req.formErrorFields["fullname"] : "",
value: req.body?.fullname ? req.body.fullname : "",
},
{
name: "email", label: "E-mail", type: "text",
err: req.formErrorFields?.email ? req.formErrorFields["email"] : "",
value: req.body?.email ? req.body.email : "",
},
{
name: "message", label: "Bericht", type: "textarea",
err: req.formErrorFields?.message ? req.formErrorFields["message"] : "",
value: req.body?.message ? req.body.message : "",
},
];
const flash = req.flash || {};
res.render("contact", {
inputs,
flash,
});
};
export const postContact = async (req, res, next) => {
// [...] (validation)
try {
// let us send an email
console.log('Yay, we could send Georgette an email now');
// set the flash message
req.flash = {
type: "success",
message: "Uw bericht is verzonden",
};
// empty the form fields
req.body = {};
return next();
} catch (error) {
console.error(error);
}
}
Validatie, Authenticate, Authorisatie & Mailing
Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default.
Installeer nodemailer
npm install nodemailer
Installeer de applicatie nodemailer op je PC of Mac:
https://www.nodemailer.com/app/
Hiermee kunnen we een e-mail server starten en testmails opvangen.
Maak een nieuw project in nodemailer
Ga naar het tabblad "Local Server" en stel zo nodig port, username en password in
Kopieer
het transporter
script
Start de server
Via het tabblad zou Server Status nu op running moeten staan
import nodemailer from "nodemailer";
const transporter = nodemailer.createTransport({
host: "localhost",
port: 1025,
auth: {
user: "project.1",
pass: "secret.1",
},
});
export default transporter;
import transporter from "./lib/MailTransporter.js";
// ...
app.get("/testmail", async (req, res) => {
try {
const mailInfo = await transporter.sendMail({
from: "noreply@parfumeriegeorgettemadelein.be",
to: "foobar@example.com",
subject: "Test mail",
text: "This is a test mail",
});
res.send(mailInfo);
} catch (error) {
res.send(error);
}
});
const mailInfo = await transporter.sendMail({
from: "noreply@parfumeriegeorgettemadelein.be",
to: "foobar@example.com",
subject: "Test mail",
// text: "This is a test mail",
html: `
<h1>This is a test mail</h1>
<p>With <em>some</em> content</p>
`,
});