How do I create a simple REST API with Node.js and Express?
Asked on Oct 01, 2024
Answer
Creating a simple REST API with Node.js and Express involves setting up an Express server and defining routes that handle HTTP requests. Here's a basic example:
// Import the Express module
const express = require('express');
// Create an instance of an Express application
const app = express();
// Define a port for the server to listen on
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// Define a simple GET route
app.get('/api', (req, res) => {
res.json({ message: 'Welcome to the API!' });
});
// Define a POST route
app.post('/api/data', (req, res) => {
const data = req.body;
res.json({ receivedData: data });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Additional Comment:
✅ Answered with JavaScript best practices.- This example uses Express to create a server that listens on port 3000.
- The "app.use(express.json())" middleware is used to parse JSON request bodies.
- There are two routes: a GET route at "/api" and a POST route at "/api/data".
- The GET route responds with a welcome message, while the POST route echoes back the received JSON data.
- To test this API, you can use tools like Postman or curl to send requests to "http://localhost:3000/api" and "http://localhost:3000/api/data".
Recommended Links:
← Back to All Questions