From the course: Node.js: Web Servers, Tests, and Deployment
Unlock the full course today
Join today to access over 23,200 courses taught by industry experts.
Serving JSON data - Node.js Tutorial
From the course: Node.js: Web Servers, Tests, and Deployment
Serving JSON data
- [Instructor] We can also use the HTTP module to create an HTTP API or a server that's primary purpose is to serve up JSON. APIs are used to serve data to client applications. So let's go ahead and start by requiring createServer. And then we'll also require our data. Now, the data is here in this file called cats.json. A little bit of simple JSON data. So let's go ahead and require ./cats. All right, so createServer. As you might expect, we'll take in the request and the response. This function is going to write some headers for us. So if 200, then our Content-Type will be text/json. We also want to call response.end and we'll say JSON.stringify our data. Finally, we need to chain on a .listen with 3000. Okay. So at this point, we should be able stop our old server. We'll make sure that we're navigated to the right place. We will run node index. This should run our server on 3000. Let's go over here and…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.