NodeJS and ExpressJS are two powerful tools you can use to create REST APIs. A REST API, or Representational State Transfer, is a style of software architecture that uses a set of protocols and standards to build web applications. In this section, we'll learn how to create a basic REST API with NodeJS and ExpressJS and how to handle errors.
Setting the environment
Before we start, we need to make sure we have NodeJS and npm (Node Package Manager) installed on our system. If you don't have them yet, you can download them from the official NodeJS website. After installation, you can verify that they are installed correctly by running the following commands in the terminal:
$ node -v $ npm -v
Next, we need to install ExpressJS, which is a web framework for NodeJS. You can install ExpressJS using npm with the following command:
$ npm install express
Creating the REST API
First, let's create a new file called 'app.js'. This will be our main file where we will configure our REST API. In the 'app.js' file, let's start by importing the ExpressJS:
const express = require('express');
Next, let's create a new instance of Express:
const app = express();
Now, let's define some routes for our API. For example, let's create a GET route to '/users' that returns a list of users:
app.get('/users', (req, res) => { res.json({ users: ['John', 'Jane', 'Bob'] }); });
Finally, let's make our application listen to port 3000:
app.listen(3000, () => { console.log('Server is running on port 3000'); });
Error handling
Error handling is a crucial part of any application. In ExpressJS, you can handle errors using error middleware. An error middleware is a function that takes four arguments: (err, req, res, next).
You can define an error middleware as follows:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
This error middleware will catch any error that occurs in the application and will log the error stack to the console, and then send a response with status 500 and the message 'Something broke!'.
It is important to note that the error middleware must be defined after all other routes and middleware, because it will only catch errors that occur in the middleware and routes that are defined before it.
In addition, you can create custom error middleware to handle different types of errors in different ways. For example, you can create an error middleware to handle validation errors and another to handle authentication errors.
Conclusion
In this chapter, we learned how to create a basic REST API with NodeJS and ExpressJS and how to handle errors. ExpressJS makes it very easy to create REST APIs and offers many useful features such as error middleware that allow us to handle errors effectively.
In the next chapter, we'll learn how to add authentication to our API and how to secure our routes with JWT (JSON Web Tokens).