14. Creating a route

If we take a look at the home page of the finished app, we can see a list of available prints, which can we'll refer to as "items".

In the coming videos, we'll be creating a endpoint that the client can use to retrieve the data for these items from the API.

On our server we're using the Express framework. You'll see at the top of the server index file that we're creating an instance of Express which we assign to a variable app.

To create our items route, we'll go to the middle of this file and use the get method of Express to declare a new GET endpoint.

The first argument to this method is the URI we wish to use, which will be /items, and the second argument is the callback method that gets called when a request is made to this URI.

It has two arguments, request and response, which are typically abbreviated to req and res.

Finally, we'll use the send method of the response object to return a JSON object to the client which simply gives a success message.

app.get("/items", (req, res) => {
  res.send({ message: "It works" });
});

Let's now run our server so it's listening:

$ npm run serve:server

Now, in our browser, we can test that this endpoint works by going to the address http://localhost:8070/items, where we see the desired response.

With that, our app is now functioning as an API, albeit a very simple one.

Discussion

2 comments