You'll learn how to handle multiple HTTP verbs in your API route (GET, POST, PATCH, PUT and DELETE). Also, you'll learn how to create a fallback 404 route in case the request doesn't match what you need.
Instructor: [0:00] Let's start by creating a route that is going to be called verbs. This route will have a function. We're going to call it handler(). This receives a req and a res. We're going to export that handler as the default export for this file.
[0:20] The next thing that we're going to do is we're going to get the method that's coming from the request, and we're going to compare it with some strings. Here, we have if the method equals to GET, then we're going to respond to the client with a status of 200, and we're sending back a json that says ({ message: "GET" }).
[0:49] Now, let's try out this endpoint. We're going to send a GET request to localhost:3000/api/verbs. We see that we get back a message that says GET.
[1:02] Let's create a fallback response. We're going to set the status to 404. We're going to send back a json that says ({ message: "Not found" )}. Now, we're sending a POST request to that same endpoint, and we should get a 404 back. Yes, indeed, that is what we got.
[1:26] Let's check the method against a POST request. I'm going to return a 200 as well. 200 here and a json that says ({ message: "POST" }). Let's try that out in our terminal. We're going to hit api/verbs with the POST method. Yep, we get back a 200 with the message POST.
[1:53] Let's do the same but with the other verbs. We're going to do this with PATCH. PATCH here. Then PUT. Last but not least, we're going to do DELETE. Let's see. We're going to send a PATCH. Now we're going to send a PUT to api/verbs. Last but not least, we're going to send DELETE. There you go.
[2:36] To recap, if we want our API Route to handle different HTTP verbs, what we have to do is we have to get the method from the req object. Then we check it against...This is strings. For instance, if you're checking for a GET, then we do a === and then GET in uppercase, same for POST, HATCH, PUT and DELETE.
[3:04] In the case that our API Route doesn't handle all the HTTP verbs, let's make sure that we create a fallback response to the client. In this case, we're going to respond with a 404 and a json message that says, "Not found."
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!