Table of Contents
Welcome to the comprehensive guide on getting started with Node.js and building your first REST API using Express.js. This tutorial is designed for beginners eager to develop scalable and efficient web services.
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser. It is built on Chrome's V8 JavaScript engine and enables developers to build server-side applications with JavaScript.
Why Use Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for building web and mobile applications. It simplifies routing, middleware integration, and handling HTTP requests.
Prerequisites
- Basic knowledge of JavaScript
- Node.js installed on your machine
- Text editor or IDE (e.g., VS Code)
- Command Line Interface (CLI) familiarity
Step 1: Setting Up Your Project
Create a new directory for your project and initialize it with npm:
In your terminal:
mkdir my-first-api
cd my-first-api
npm init -y
Step 2: Installing Dependencies
Install Express.js using npm:
npm install express
Step 3: Creating Your Server
Create a new file named app.js in your project directory. This file will contain your server code.
Open app.js and add the following code:
app.js
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello, World! Welcome to your first REST API with Express.js');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 4: Running Your Server
In your terminal, run the server:
node app.js
You should see: Server is running on http://localhost:3000
Step 5: Testing Your API
Open your browser or use a tool like Postman to test your API:
Navigate to: http://localhost:3000
You should see the message: Hello, World! Welcome to your first REST API with Express.js
Next Steps
Congratulations! You've successfully set up your first REST API with Node.js and Express.js. From here, you can expand your API by adding more routes, handling different HTTP methods, connecting to databases, and more.
Happy coding!