In this section, we'll explain how to set up a basic HTTP server using Node.js and Express. This server setup is a fundamental part of any web application, allowing it to listen for and respond to incoming requests.
On the index.js file of root directory
http: This core Node.js module is used to create an HTTP server.app: This is the Express application we configured in express.config.js inside src/config folder.http.createServer(app): This line creates an HTTP server instance using the Express app as the request handler.5500 for our server.server.listen(5500, '127.0.0.1', callback): This function makes the server listen on the specified port (5500) and hostname (127.0.0.1 which is localhost).Starting the Server:
Execute the command to start the server
npm start
The listen method starts the server and begins waiting for incoming connections on the specified port and hostname.
If the server starts without errors, it logs:
Server is running on port 5500
press ctrl+c to discontinue server.....
Handling Errors:
server.listen checks if there are any errors (if (!err)). If there are no errors, it logs the success message. If there were an error, you could add an else statement to handle it (e.g., log the error message).Stopping the Server:
Ctrl+C in the terminal where the server is running.Here is the code snippet that sets up the server connection:
const http = require('http');
const app = require('./src/config/express.config');
const server = http.createServer(app);
server.listen(5500, '127.0.0.1', (err) => {
if (!err) {
console.log("Server is running on port 5500");
console.log("press ctrl+c to discontinue server.....");
}
});