Setting Up Your Environment
In this section, we will install Node.js and Express to start our project.
- Download and install Node.js from Node.js official website.
- Verify installation by running
node -v
andnpm -v
in your terminal.
This tutorial provides a step-by-step guide to creating a simple RESTful API using Node.js and the Express framework. Learn how to set up your environment, create routes, and handle requests.
In this section, we will install Node.js and Express to start our project.
node -v
and npm -v
in your terminal.Node.js and npm should be installed successfully.
Use the following commands to create a new project directory and initialize it.
mkdir my-api
cd my-api
npm init -y
A new Node.js project is created with a package.json file.
Run the following command to install Express in your project.
npm install express
Express is installed and added to your package.json file.
Create a file called server.js
and add the following code to set up your server.
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
The server should start and listen on port 3000, displaying 'Server is running on http://localhost:3000'.
Modify your server.js
to include the following endpoints:
app.get('/api/data', (req, res) => {
res.json({ message: 'GET request received' });
});
app.post('/api/data', (req, res) => {
res.json({ message: 'POST request received' });
});
You can make GET and POST requests to '/api/data' and receive JSON responses.
Use Postman or curl to test your API:
curl -X GET http://localhost:3000/api/data
curl -X POST http://localhost:3000/api/data
You should receive JSON responses for both GET and POST requests.