Express Module #54 Flashcards

1
Q

What is Express.js? What is it used for?

A

Express. js is a Node. js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node. … js framework for quickly creating dynamic end-to-end REST APIs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Making a webserver was a dozen or so lines of code using vanilla node.js. Using express it’s only 4 lines. What are those lines?

A
const express = require('express')
const app = express()

app. get(‘/’, (req, res) => res.send(‘Hello World!’))
app. listen(3000, () => console.log(‘Server ready’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

There is a method for every HTTP verb: get( ), post( ), put( ), delete( ), patch( ): How are they written? Hint: they all use the same syntax.

A

app. get(‘/’, (req, res) => { /* / })
app. post(‘/’, (req, res) => { /
/ })
app. put(‘/’, (req, res) => { /
/ })
app. delete(‘/’, (req, res) => { /
/ })
app. patch(‘/’, (req, res) => { /
*/ })

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The HTTP Verbs accept a callback function. How does that look?

A

(req, res) => res.send(‘Hello World’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What objects are returned from the (req, res) => res.send(‘Hello World’) callback

A

Request and response objects

Request is the HTTP request. It gives us all the request information, including the request parameters, the headers, the body of the request, and more.

Response is the HTTP response object that we’ll send to the client.

What we do in this callback is to send the ‘Hello World!’ string to the client, using the Response.send() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are a few things that are held in the request?

A
These all seemed fairly self explanatory...
.app 	
.baseUrl 	
.body 	
.cookies 	
.hostname 	
.ip 	
.method 	
.params 	
.path 	
.protocol 	
.query 	
.secure 	
.signedCookies 	
.xhr
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you return query string parameters (‘?’, ‘&’) you see these all the time in urls.

A

By populating the Request.query object
Example, look at the console.log expression.

    const express = require('express')
    const app = express ( )
app.get('/', (req, res) => {
console.log(req.query)
})

app.listen(8080)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens if there aren’t any query parameters?

A

Then it returns an empty object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What’s the appropriate loop to use on an empty query parameters object or any empty object?

A

The for in loop. In this situation, it looks like this:

for (const key in req.query) {
console.log(key, req.query[key])
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

** How can you retrieve the POST query string parameters using express? And what are they most commonly used for?

A

POST query parameters are sent by HTTP clients for example by forms, or when performing a POST request sending data.

How can you access this data?

If the data was sent as JSON, using Content-Type: application/json, you will use the express.json() middleware:

const express = require('express')
const app = express ( )
app.use(express.json( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you send an empty response (without a body)

A

res.end( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you set the HTTP response header?

A

Use the Response.status():
Which actually looks like this i action?

res.status(404).end()
or
res.status(404).send(‘File not found’)

res.status(404).end()
or
res.status(404).send(‘File not found’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What method sends a JSON response?

A

You can send JSON to the client by using Response.json(), a useful method.

It accepts an object or array, and converts it to JSON before sending it:

res.json({ username: ‘Flavio’ })

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How are cookies managed? That is to say which method?

A

Use the Response.cookie() method to manipulate your cookies.

Examples:

res.cookie(‘username’, ‘Flavio’)

domain The cookie domain name
expires Set the cookie expiration date. If missing, or 0, the cookie is a session cookie
httpOnly Set the cookie to be accessible only by the web server
maxAge Set the expiry time relative to the current time, expressed in milliseconds
path The cookie path. Defaults to ‘/’
secure Marks the cookie HTTPS only
signed Set the cookie to be signed
sameSite Value of SameSite

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How can a cookie be cleared

A

res.clearCookie(‘username’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How are HTTP headers accessed?

A

You can access all the HTTP headers using the Request.headers property:

app.get(‘/’, (req, res) => {
console.log(req.headers)
})

17
Q

If you want or need to modify a header for a response?

A

You can change any HTTP header value using Response.set():

res.set(‘Content-Type’, ‘text/html’)

There is a shortcut for the Content-Type header, however:

res.type('.html')
// => 'text/html'
res.type('html')
// => 'text/html'
res.type('json')
// => 'application/json'
res.type('application/json')
// => 'application/json'
res.type('png')
// => image/png:
18
Q

How would you set up a redirect?

A

Redirects are common in Web Development. You can create a redirect using the Response.redirect() method:

res.redirect(‘/go-there’)

This creates a 302 redirect.

A 301 redirect is made in this way:

res.redirect(301, ‘/go-there’)

You can specify an absolute path (/go-there), an absolute url (https://anothersite.com), a relative path (go-there) or use the .. to go back one level:

res. redirect(‘../go-there’)
res. redirect(‘..’)

You can also redirect back to the Referer HTTP header value (defaulting to / if not set) using

res.redirect(‘back’)

19
Q

What is routing as it pertains to a webserver?

A

Routing is the process of determining what should happen when a URL is called, or also which parts of the application should handle a specific incoming request.

This creates a route that maps accessing the root domain URL / using the HTTP GET method to the response we want to provide.

20
Q

What if you wanted to utilize dynamic server-side html templates?

A

npm install pug

const express = require("express")
const app = express()
app.set("view engine", "pug")

To get all of the deets on PUG go to:
https://pugjs.org/api/express.html

21
Q

What’s the process for creating a page?

A

Create an about view:

app.get(“/about”, (req, res) => {
res.render(“about”)
})

and the template in views/about.pug:

p Hello from Flavio

This template will create a p tag with the content Hello from Flavio.

You can interpolate a variable using

app.get(“/about”, (req, res) => {
res.render(“about”, { name: “Flavio” })
})

Using this:

p Hello from #{name}

To get all of the deets on PUG go to:
https://pugjs.org/api/express.html

22
Q

How would you expose images and css at the root level?

A
const express = require('express')
const app = express()

app.use(express.static(‘public’))

/* … */

app.listen(3000, () => console.log(‘Server ready’))

If you have an index.html file in public/, that will be served if you now hit the root domain URL (http://localhost:3000)

23
Q

What function do sessions perform?

A

To identify users. When implemented, every user of your API or website will be assigned a unique session, and this allows you to store the user state.

24
Q

How are sessions for express installed?

A

npm install express-session

and once you’re done, you can instantiate it in your application with

const session = require(‘express-session’)

This is a middleware, so you install it in Express using

const express = require('express')
const session = require('express-session')
const app = express()
app.use(session({
  'secret': '343ji43j4n3jn4jk3n' //add a random string here
}))
25
Q

Finally FORMS!!! How can you extract data that is in a POST request body.

A

To extract it, you will need to use the express.urlencoded() middleware, provided by Express:

const express = require('express')
const app = express()

app.use(express.urlencoded())

Now, you need to create a POST endpoint on the /submit-form route, and any data will be available on Request.body:

app.post('/submit-form', (req, res) => {
  const username = req.body.username
  //...
  res.end()
})

Don’t forget to validate the data before using it, using express-validator.