In this lesson we’ll install json-server
as a dependency of our project so we can explore making API calls in a Redux-friendly way. We’ll update the scripts in package.json
to allow us to run the server and verify it is responding by issuing a curl
command.
In order to set up a local server to test API calls against, we're going to add JSON-server as a dependency to this project. We'll do that using Yarn add JSON pick new server. Now that that's installed, let's get our project set up to use it.
I'm going to start by adding a new file to the root of my project, which I'm going to call "db.json." In db.json, I'm just going to paste in an object that has a to-dos property, which is an array of to-do objects, and I can save that file.
Then I'm going to open up package.json, and I'm going to add a script. I'm going to call that script "dev-server," and this is going to start up our JSON-server.
The command for that will be JSON-server. Then we're going to give it a specific port, so we're going to specify -p 8080, and then we're going to follow that up with the name of the file that's going to hold our data.
We'll save this, and then back in my terminal, I can try this out by running Yarn dev-server. We'll see that it issues our JSON-server command with our port and our file, and that we have the server running.
With that server running, I'm going to open a new tab in my terminal, and I'm just going to issue a curl command to get my to-dos. We'll curl to localhost:8080/todos and it returns the objects that are sitting in our db.json file.
How come you didn't add json-server package to dev dependencies?
How come you didn't add json-server package to dev dependencies?
Because for this particular example, we deploy the entire thing to a server in the last video and json-server
is part of the "production" deployment. Not something I would use for a real production app, but getting into setting up a real server was beyond the scope of this course.
Copy and paste and using a setup that cuts off half of the code. Good job!
Copy and paste and using a setup that cuts off half of the code. Good job!
The lesson includes a link to the code. Here is the direct link to that file:
https://github.com/eggheadio-projects/egghead_react_redux_course/blob/15-json-server/db.json