Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
In this video, we'll add functionality to our app that will allow the client to request a random quote.
-
0:00
Before I show you how to create a random route,
-
0:02
I encourage you to give it a try yourself.
-
0:04
Look for the correct method to use in the records.js file, look at code
-
0:08
we've written so far to remember syntax and how things should be structured and
-
0:12
go ahead and write the route in the routes.js file.
-
0:15
Pause the video, give it ago, and remember, this challenge is open book.
-
0:21
How’d you do?
-
0:22
If you got stuck somewhere along the line, don’t sweat it.
-
0:25
Watch my solution, finish the course, sleep on it, come back and try again.
-
0:28
If this is pretty new to you, you’ve absorbed a ton of information throughout
-
0:32
this course and sometimes your brain just needs a little time to process it all.
-
0:35
Okay, so let’s dig into it.
-
0:37
I’m simply requesting information, so I’m going to write a GET request.
-
0:41
I'm going to put our new GET request route just underneath
-
0:45
our other two GET requests.
-
0:46
So right after the route that gets a specific quote.
-
0:50
And I will go ahead and move our comment, Up here.
-
1:03
I'll start with router.get.
-
1:05
And we want to respond to a get request to /quotes/quote/random.
-
1:13
The next parameter is an anonymous function that accepts the request,
-
1:17
response, and next objects.
-
1:25
Now I'll set up a try catch block, passing any errors to our global error handler.
-
1:37
Inside the try block, I'll await the results of the records.getRandomQuote()
-
1:42
method, and save it to a variable called quote.
-
1:53
Finally, I'll send back a response containing the random quote as JSON.
-
2:00
I can also route my callback in the asyncHandler function so
-
2:03
I don't have to use tryCatch.
-
2:16
Let's make sure the server is running, go to Postman, and test this out.
-
2:20
Remember, I've set up a router so that all requests must now be sent to /api.
-
2:25
So I will send a get request to /api/quotes/quote/random.
-
2:37
And fantastic, we are receiving random quotes.
You need to sign up for Treehouse in order to download course files.
Sign up