Transcript from the "Serving API Endpoint" Lesson
>> Kyle Simpson: Now that we're serving up files, the next question we might ask is, how could I respond to AJAX requests? How could I have an API endpoint for my code? So in our handleRequest, back to our handleRequest function, we're gonna set up an if statement. That if the incoming request looks like an API request, we're gonna handle it manually.
>> Kyle Simpson: I don't have it hard-coded, okay, we'll just pick one. Let's say, let's call it get-records, that's the API endpoint that we want to handle specifically. So don't need any regular expression for that, I can just say (rec.url == "/get-records"). And if that's the case, we wanna handle it manually, otherwise we wanna serve up,
>> Kyle Simpson: So what do we want to respond with, when there is a request for the get-records? Well, we have a function already filled in for you, which is the getAllRecords() from our previous exercise. This one should be able to connect to our database, and pull out that array of information, and return it.
[00:01:40] So really, all we need to do is call the getAllRecords(), and json.stringify that, and send that out as a JSON response. Quick note that if, for some reason, at this moment, your SQLite wasn't working? You can comment that version out, and just use this hard-coded one to send some data.
[00:02:00] Just so you get the sense of how we're sending out JSON responses. Okay, so let's first say, records = await getAllRecords().
>> Kyle Simpson: And then how are we gonna send out a JSON response? Well, it's similar to what we did before. We're gonna say res.writeHead, and we're gonna say 200, and here, we need to send a content type,
>> Kyle Simpson: That is application/json, and also, since it's an API that we we don't want to be unnecessarily cached? We should send out a Cache-Control header that says, no-cache.
>> Kyle Simpson: And then we're gonna say res.end, and we'll just json.stringify the records array. Okay, so let's restart our server,
>> Kyle Simpson: And let's test to see if we are, in fact, able to get,
>> Kyle Simpson: A response from get-records, and there's our string of JSON that's coming in, so that's a good sign. That now means that from our web page side, we can make an AJAX call, and get that data, and then print it.