Express Flashcards

1
Q

What does CRUD mean? What are the adjacent API calls?

A

Create, read, update, delete

Post, get, put, delete

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

How do you create the express app in a server.js file? How do you make it listen on port 3000?

A

const express = require(“express”)
const app = express()

app.listen(3000)

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

How would you install the ejs view engine to render html files? How do render it in an express method and pass values to the ejs file? How do you use those values? What should you add to make sure the ejs file does not return an error?

A

To install ejs:

npm i ejs

Then on your express app in server.js:

app.set(‘view engine’, ‘ejs’)

The html file needs to rename the extension to .ejs instead of .html. Install EJS language support to see syntax highlights (vscode, not sure if it works for other editors). Then to render it in express method, use res.render(“index”).

Note: index.ejs needs to be in a views folder because that is the default path for render.

We can use something like res.render(“index”, { text: “World” }) to send variables to the ejs file, which can be used in the ejs file.

<body>
Hello <%= text %>
<\body>

This will output Hello World because the text variable was “World”.

<body>
Hello <%= locals.text || ‘Default’ %>
<\body>

Using locals.anything will not return an error because locals always exists here. It simply won’t print the variable if the value inside locals hasn’t been defined. “Default” will print instead if that is the case.
</body></body>

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

How would you send a status and value from an express method? send JSON? send a downloadable file?

A

res.status(500).send(“hi”)

This will send “hi” and an internal server error status

res.json({ message: “Error” })

res.download(“server.js”)

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

What npm command creates a general package.json? What do you need to install so you can restart your server easily? What goes in the script section of package.json to make this work?

A

npm init -y

Creates the package.json file

npm i —save-dev nodemon

To install nodemon

In scripts:

“devStart” : “nodemon server.js”

npm run devStart

This will now restart the server easily whenever you save a file.

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

How do you install express with node?

A

npm i express

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

If you have /users methods for example, what can you do to organize these method calls?

A

Create a folder called routes and a new file called users.js. Import express, the same as in server.js, except instead of making app with express(), make a router:

const router = express.Router()

router.get(…) will be how we do the functions now. Instead of typing /users as the start of each of these paths, it will be implied, so /new is equivalent to /users/new

At the bottom of the file:

module.exports = router

Back in server.js, import the file:

const userRouter = require(‘./routes/users’)

Then mount the router onto the server.js app:

app.use(‘/users’, userRouter)

Now any API calls that begin with /users will route to the users

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

If an express method has a route with /:id for example, how do you use the id value in the function?

A

In a string:

${req.params.id}

Probably works without the brackets and dollar sign when not used in a string. Not sure though.

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

What do you need to remember about placing dynamic routes?

A

Always put dynamic routes at the bottom of the file.

If I have a dynamic route of /:id and another static route /new below it, calling /new is still going to use the /:id route and set req.params.id to “new”. That’s because it always picks the first route that matches from top to bottom.

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

How can you shorten the 4 CRUD methods that map to the route “/:id”?

A

Instead of using router.get, router.put, etc., do this:

router.route(“/:id”).get(…).put(…).etc….

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

What does the router.param() function do? How do you use it? What do we call this function?

A

It allows you to run code whenever a method has a given parameter. So for the 4 CRUD methods that include /:id, calling any of them will run this code.

router.param(“id”, (req, res, next, id) => {
req.user = users[id]
next()
})

This is called middleware. It is code that runs between the start and the end of the request.

Note: you must use the function “next()” to indicate that we should move on to the actual method call. I believe this is the case with all middleware.

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

What is middleware? What special parameter is unique to these functions that aren’t included in the regular CRUD functions?

A

Middleware is code that runs between the start of the request and the end of the request. The special parameter used in these function is next(). This indicates that the middleware function is complete and you can move on to the next function.

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

How do you create a middleware logger? How do you make it run on all requests? Specific request?

A

This is the custom middleware function you can create:

function logger(req, res, next) {
console.log(req.originalUrl)
next()
}

It simply prints the original URL to the console, but you can make it do whatever you want. To make this run whenever a function is called, use:

app.use(logger)

The middleware function will only activate on requests declared after the app.use() statement, so if you want it to apply to everything, put the statement at the top of the file before any methods are declared.

To make it run for a specific function only, don’t use the app.use(logger) statement. Simply put the name of the method as an additional argument in the CRUD method you want to use it. So:

app.get(“/“, logger, (req, res) => {…}

You can pass any number of middleware functions into the CRUD functions. Just make another comma and insert before or after “logger,”

All of this works on specific routers too, so in a users.js file you can do router.use(logger) after pasting the logger function into the file too.

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

If you want to serve html files (not ejs) without having to render it with a request and/or view engine, what tool would you use?

A

The built-in middleware function express.static(). If we have a folder called “public” in the same folder as server.js, and “public” holds html files, we could use:

app.use(express.static(“public”))

This sets the default folder to public. When we go to the default url plus the file name inside the “public” folder (localhost:3000/index.html), the html file will be served. If there are folders within “public” which contain html, we can navigate through them using the url to get those other pages. So if test.html is in public/test/test.html, we could use localhost:3000/test/test.html to get it.

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

When you submit an ejs form with an action that maps to a CRUD method, how do you retrieve the variables of that form? How do you send information back to the form? Why would you do this?

A

Each form has inputs, and those inputs have an inner html field called “name”. When a form is submitted, the req object in the express method has a .body element. So if one of the inputs had name “firstName”, in the express method called, use req.body.firstName to get the value provided to that input.

In order to access the body element of a req object, however, you must do something first. Express, by default, does not allow you to access it. You must use some middleware. At the top of your server.js file, use:

app.use(express.urlencoded({ extended: true }))

To send info back to the form, you can use res.render(‘users/new’, { firstName: req.body.firstName })

This renders the page back to the way it was originally while keeping the “firstName” value the same as what the person typed in. That way, each time the person presses the submit button, the page won’t reload with an empty input if it was an error. This is good UX/UI practice.

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

What does the res.redirect() method do? When might you use it?

A

It redirects the url to wherever you want. So if a user signs in and the user is valid, you could redirect the user to their specific user url.

You could also make routing buttons, so on click, it fetches the particular method that redirects the url to that page.

17
Q

What middleware would you use to allow you to parse json info from a request body?

A

app.use(express.json())

18
Q

What is a query parameter? How do you use it?

A

A query parameter is a parameter passed through a url after a question mark. So for example:

localhost:3000/users?name=Kyle

This will be stored in our request body as req.query.name. So if you did:

console.log(req.query.name)

“Kyle” would be printed to the console.

19
Q

Are the req and res objects specific to each function from start to finish?

A

No. If you make a field called req.admin and set it to true in one middleware function, calling req.admin in the next middleware function with return true.

Likewise, if we call res.send() or one of those ending functions anywhere in the middleware, it will end the function calls, whereas calling next() will move on to the next function in line.

20
Q

Is next() like a return statement? Does res.send() stop the server execution? How do you run middleware code at the end of all the request functions have executed?

A

No. Next calls the next function, so if you have a res.send() after it, that send statement will still be run after the other code is run. If you want the function to essentially terminate after next(), it must be the last statement in the function or you must type a return statement after the next() call.

res.send() is also not a final statement. You can send back to the client and still have code running after it. Another reason why next() should be handled carefully, because a deeper functions call to res.send() does not ensure more code won’t be executed after.

If you use app.use() on a middleware function at the top of the page, begin the function by calling next(). Add the code after that call to be run after the rest of the code is done executing.

21
Q

Recall the syntax to create a CRUD method in express.

A

app.get(‘/path’, middleware, (req, res) => {

}

22
Q

What do you need to put before any mongoose calls to the database? Like item.find({})?

A

You have to put “await item.find({})” because without “await”, it will try to send the object before the database call is finished, which will cause as error.

23
Q

How does MongoDBAtlas name collections based off of information defined in mongoose and express?

A

The collection name in the MongoDB database will be the name given in the model, converted to lower case, with an ‘s’ at the end. So posting an item to the data base with this mode:

const Portfolio = mongoose.model(‘PortfolioItem’, portfolioSchema);

will post the item to the collection “portfolioitems” in the database. It will also create the collection if it doesn’t already exist.