Building a basic server with NodeJS is a fundamental task for any developer who wants to create robust and efficient APIs. In this chapter, we'll cover how to define routes and endpoints to create a basic server in NodeJS.
First steps
Before we start creating our server, we need to install NodeJS and NPM (Node Package Manager) on our system. Both are essential tools for developing applications in NodeJS. You can download and install them from their respective official websites.
Creating a basic server
After installing NodeJS and NPM, let's start creating our server. First, create a new directory for your project and navigate to it using the terminal. Then initialize a new NodeJS project with the 'npm init' command. This will create a new 'package.json' file in your directory, which contains information about your project and its dependencies.
Now, let's install the 'express' package, which is a framework for NodeJS that simplifies the creation of web servers. You can install express with the command 'npm install express'.
With express installed, let's create a new file called 'server.js'. This will be the main file on our server. In 'server.js', let's import express and create a new instance of it:
const express = require('express');
const app = express();
Defining routes and endpoints
With our server created, we can now define routes and endpoints. Routes are the paths that users can access on our server, while endpoints are the functions that are executed when a specific route is accessed.
Let's define a simple route that returns a welcome message when the user accesses the root route ('/') of our server:
app.get('/', (req, res) => {
res.send('Welcome to our NodeJS server!');
});
In this code, 'app.get' is a function that defines a new endpoint for the '/' route. The function takes two arguments: 'req' and 'res'. 'req' is the request object, which contains information about the user's request, such as URL parameters and body data. 'res' is the response object, which is used to send a response to the user.
Now, let's define a route that accepts parameters. Let's create a '/users/:id' route, which returns the details of a specific user based on their ID:
app.get('/users/:id', (req, res) => {
const id = req.params.id;
// Here you would normally fetch user details from a database
res.send(`User ID details: ${id}`);
});
In this code, ':id' is a route parameter. You can access the value of this parameter using 'req.params.id'.
Conclusion
With that, we have a basic NodeJS server with some defined routes and endpoints. To start the server, you can use the command 'node server.js' in your terminal. Now, you can access your server at 'http://localhost:3000' in your browser or using a tool like Postman.
Defining routes and endpoints is an essential part of creating APIs in NodeJS. With practice, you will be able to create more complex servers with multiple routes and endpoints, and integrate them with databases and other technologies.