In our journey of learning about creating APIs in NodeJS, we reached the crucial point: creating a basic server. In this chapter, we are going to dive into the concept of API and understand how we can create a basic server using NodeJS.
To begin with, it's important to understand what an API is. API is the acronym for Application Programming Interface, or Application Programming Interface, in Portuguese. In simple terms, an API is a set of rules that allows different software to communicate with each other. It defines the methods and data that an application can use to communicate with other applications.
In terms of web development, an API is a bridge between the front end and back end of an application. It allows the front end (the user interface) to communicate with the back end (the server and the database) in a structured and secure way.
With that in mind, let's move on to our main objective: creating a basic server with NodeJS. NodeJS is an open source platform that allows the execution of JavaScript code on the server side. This means that with NodeJS we can create web servers capable of processing requests and sending responses to clients.
To create a basic server with NodeJS, we first need to install NodeJS on our system. Once NodeJS is installed, we can start writing our code.
The first step to create a server is to import the NodeJS 'http' module. This module contains functions and methods needed to create a server. To import the 'http' module, we use the NodeJS 'require' function, as shown below:
const http = require('http');
With the 'http' module imported, we can now create our server. For this, we use the 'createServer' function of the 'http' module. This function receives a callback function that is called whenever the server receives a request. The callback function takes two arguments: a request object and a response object. The request object contains information about the incoming request, while the response object is used to send a response to the client.
const server = http.createServer((req, res) => {
res.end('Hello, World!');
});
In this example, whenever the server receives a request, it sends the response 'Hello, World!' for the customer.
Finally, we need to start our server. For this, we use the 'listen' method of the server object. This method takes two arguments: the port on which the server should listen and a callback function that is called when the server starts listening. The callback function is optional and is usually used to display a message indicating that the server is up and running.
server.listen(3000, () => {
console.log('Server running on port 3000');
});
With this, we have a basic server running on port 3000. Whenever it receives a request, the server will send the response 'Hello, World!' for the customer.
This is just the beginning of our journey into creating APIs with NodeJS. In the next few chapters, we'll learn about routes, middleware, databases, and more. Stay tuned and keep learning!