Select all e's in the string "This is an example."
Use the star operator - zero or more (of what's right before it)
/e*/
This is an example
Select all "at", or "att"s in the string: What is the matter?
? optional operator - zero or one (of what's right before it)
/at?t/
What is the matter?
The at in "What" matched zero times. The att in matter matched one time.
Select the "att" in the phrase "at attribute"
Use + plus operator - one or more (of what's right before it)
/at+t/
at attribute
Match as follows: what is the pattern?
Use the . operator. Matches any one character.
/e./
what is the pattern?
Match the following: what is the pattern?
Again, use the dot operator, but this time following a space
/e ./
what is the pattern?
Match the following: The text is the thing.
Use the hat (^) operator: Start of input
/^The/
The text is the thing.
Match the following: She went to the store then just got home from the store.
Use the dollar operator ($) - matches only at the end of the input string
/store$/
She went to the store then just got home from the store
Match the following: Who ate my name?
Use the [] operator. Selects any one of the characters inside the brackets
/a[tm]e/
Who ate my name?
Select the following: What is the pattern?
Use the grouping operator (). Matches the optional characters with the zero or more operator (?)
/at( is)?/
What is the pattern?
or
Is your name Pat?
What is the regexp shorthand for whitespace?
\s
- white space
What is the regexp shorthand for digit?
\d
- digit
What is the regexp shorthand for word char?
\w
- word char
What is the regexp for NOT a digit?
\D
- not a digit
What is the regexp for not a word char?
\w
- not a word char
How do you use re's in JavaScript?
const re = /EX$/
re.test('learning about REGEX');
Write in JavaScript a regExp that will replace all occurrences of 'e' in a string with 'x';
const re = /e/ig;
const str = "These have e's in them.";
console.log(re, 'X');
Using key/value pairs as replacement strings, write JavaScript that will replace a string with the values in the key/value pairs.
const di = { name: `Mimi`, age: 2 };
const str = `My name is %name% and I am %age% years old`;
re = /%\w+%/g;
const replaced = str.replace(re, match => {
const key = match.replace(/%/g, ``);
return di[key];
});
console.log(replaced);
Identify the five parts of a URL given the following URL:
https://example.com:8042/over/there?name=ferret#nose
Scheme | Authority | Path | Query | Fragment |
---|---|---|---|---|
https | example.com:8042 | /over/theme | name=ferret | nose |
Identify at least 3 protocols handled by the browser
IncomingMessage
object ...How is an IncomingMessage object usually represented by?
The req
variable.
In your JavaScript, how would you access the headers sent by a client (like a Web Browser) as part of the HTTP request?
console.log(req.headers);
Usually prints something like:
{ 'user-agent': 'curl/7.22.0',
host: '127.0.0.1:8000',
accept: '*/*' }
How would you access the HTTP method of a request?
console.log(req.method);
//prints out the method like `GET` or `POST`
How would you access the path of a request?
console.log(req.url);
In Node, what is IncomingMessage
a subclass of?
stream.Readable
- so we can read it like a stream.
Can with use for await..of
with a stream.Readable
?
Yes, because streamReadable> is an
async iterable
. Using for await..of
with stream.Readable
we can get each chunk of data from the stream and we can concatenate them back together.
How would you use IncomingMessage
to read the stream of content for requests that have a body?
let body = '';
for await (let chunk of req) {
body += chunk;
}
ServerResponse
object ...How would you write the status code for a ServerResponse
object?
res.statusCode = 404;
How would you write the message for a ServerResponse
object?
res.statusMessage = 'Page not found';
How would you write the content of the body of a ServerResponse
object?
res.write(body);
-- assuming the body is a big string of HTML...
How would you properly end the response to indicate to the client (like a Web browser) that all content has been written?
res.end();
... without a string or res.end(rest_of_body)
... assuming rest_of_body is more HTML.
What do you need to run an express server?
You need to require the express
package
const express = require('express');
const app = express();
Then start your express server.
const port = 8000;
app.listen(port, () => console.log(`App listening on port ${port}...`));
How would you set a default endpoint for your express server?
app.get('/', (req, res) => {
res.send('Hello World!');
});
How would you use pattern matching to catch all endpoints that have the string 'pictures' in it?
Use pattern matching to match HTTP request paths to route handlers
The following path matches /pictures followed by anything: /pictures/summer, /pictures/prom
app.get(/^\/pictures\/.+$/i, (req, res) => {
res.send('Here are some pictures');
});
How would you match URL paths that have a number in the route parameter's position?
app.get('/pictures/:id(\\d+)', (req, res) => {
res.send('Here is a single picture');
});
Howe would you write the following HTML in Pug?
<html>
<head>
<title>Pug Demo</title>
</head>
<body>
<h1>Pug Demo</h1>
<ul>
<li><a href="google.com">This is a link to google.com</a></li>
<li><span class="yellow">This is a span with class='yellow'</span></li>
</ul>
<h2>And now some colors</h2>
</body>
</html>
html
head
title Pug Demo
body
h1 Pug Demo
h2 Pug allows you to do many things
ul
li: a(href='google.com') This is a link to a google.com
li: span.yellow This is a span with class='yellow'
h2 And now some colors
How do you pass data to Pug templates to generate dynamic content?
res.render
li= color
) when assigning the valueWrite the JavaScript in your Express server to return the title, header, and a colors array to your Pug page.
app.get('/pug', (req, res) => {
res.rendjer('eod', {
title: 'EOD demo',
header: 'Pug demo',
colors: ['blue', 'red', 'green']});
});
Write the Pug code to render the variables title, header, and each of the colors in the color array in your Pug file.
html
head
title= title
style
include style.css
body
h1 This is the #{header} page which does string interpolation.
p
- const a = 1 + 2; //Look! we can do inline javascript that doesn't output!
= `The answer is ${a}` //Look this runs some inline javascript that does output!
each color in colors
li= color
What do you need to do in order to put all of your routes having to do with Users in a separate file from app.js?
In your userRoutes.js file, require the express package, then declare a constant of express.Router
const express = require('express');
const userRoutes = express.Router();
//Because this sub-router is registered on /users "app.use('/users', userRoutes);" in app.js), it will match the route /users/questions
userRoutes.get('/questions', (req, res) => {
res.send('Answers');
});
Then you need to tell app.js that you're going to use these routes:
app.use('/users', userRoutes);
In Pug, how would you create a div with the id of main
div#main
In Pug, how would you create a div with a class of blue?
div.blue
How would you tell pug to ONLY render if the value of isEOD is true?
In your app.js: res.render('layout', { isEOD: true });
In your pug file:
if isEOD
h2 Welcome back!
else
h2 Keep coding!
How would you send a Pug file dynamic information, and write a combination of static text and the dynamic values in the Pug file?
First, in the app.js send your dynamic values:
res.render('layout', {
title: 'Pug demo page',
header: 'interpolation'
});
Then, in your Pug file, interpolate the values received:
html
head
title= title
body
h1 Pug does #{header}
How would you use iteration to generate multiple blocks of HTML based on data provided to the template? For instance, say you have a set of colors in an array.
First, send your colors array to the Pug file as an object with an array:
app.get('/pug', (req, res) => {
res.render('eod', {colors: ['blue', 'red', 'green']});
});
Then, in your pug file, iterate through the array referenced by the key "colors"
ul
each color in colors
li= color
What two attributes should an HTML form possess?
<form action="/users" method="post">
What are the 3 types of action attributes for form elements?
What is the method attribute on a form element?
The method attribute defines how the data will be sent?
What methods cannot be used on a form element?
PUT, DELETE, PATCH or any methods other than GET and POST.
What happens with the form method is POST?
The form data is appended to the body of the HTTP request?
What would you have to use if you required to PUT, DELETE, or use any other method than GET or POST in an HTML form?
You would have to use AJAX requests using the fetch API, for example.
How would you create an HTML form using a Pug template engine?
form(method="post" action="/users")
input(type="hidden" name="_csrf" value=csrfToken)
label(for="username") Username:
input(type="username" id="username" name="username" value=username)
label(for="email") Email:
input(type="email" id="email" name="email" value=email)
label(for="age") Age:
input(type="age" id="age" name="age" value=age)
label(for="password") Password:
input(type="password" id="password" name="password")
input(type="submit" vlaue="Sign Up")
What is a Cross-Site Request Forgery exploits?
CSRF attacks exploit the trust a Web application has in an authenticated user.
Maria, an attacker, wants to trick Alice into sending the money to Maria instead. The attack will comprise the following steps:
How would you guard against Cross-Site Request Forgery exploits?
By using the csrf package available to Node.
What steps must you use to use the csrf package?
On your express server, use csrfProtection middleware:
const csrf = require("csurf");
const csrfProtection = csrf({cookie: true });
app.get('/', csrfProtection, (req, res) => {
res.render('index', {title: 'User List', users, errors: [], csrfToken: req.csrfToken() });
});
app.post('/users', csrfProtection, checkFields, (req, res) => {
if (req.errors.length >= 1) {
res.render('index', { errors: req.errors, users });
req.errors = [];
return
}
const { username, email, password } = req.body;
const user = ( un: username, email, password };
users.push(user);
res.redirect('/');
});
In your html, use a hidden input for your csrfToken:
form(method="post" action="users")
input(type="hidden" name="_csrf" value=csrfToken);
...
What do you need to parse incoming request body form data?
The built-in express.urlencoded() middleware
app.use(express.urlencoded({
extended: true,
}));
Why do you need to use urlencoded middleware to parse the request body?
If you look at a typical POST request, it does not come in a JSON form:
curl --request POST \
--url https://olrn6x3n19.sse.codesandbox.io/test \
--header 'content-type: application/json' \
--data '{
"json-parsing": "just with Express",
"no": "body-parser"
}'
However, after parsing the body:
{"json-parsing":"just with Express","no":"body-parser"}
What is data validation?
Data validation is the process of ensuring that the incoming data is correct.
Why is it necessary for the server to validate incoming data?
Even though you could add validations on the client side, client-side validations are not as secure and can be circumvented. Take for example the "required" setting on a form input. A savvy user could open up dev tools and set required: false, and pass through the now invalid request. Because client-side validations can be circumvented, it's necessary to implement server-side data validations.
If we didn't have server-side validations, what error code might be returned?
500: Internal Server Error. We likely tried to update a database with invalid data and the database returned an error, causing the 500 error.
Why would we want to perform server-side validations?
By performing server-side validations we are more likely to catch errors and return more accurate returned responses, such as a 400-level response.