const express = require('express');
const bodyParser = require('body-parser');
// Initializing Express app
const app = express();
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// Sample array to store data
let dataArray = [];
// Route to handle GET request
app.get('/data', (req, res) => {
res.json(dataArray);
});
// Route to handle POST request
app.post('/data', (req, res) => {
const newData = req.body;
dataArray.push(newData);
res.status(201).json(newData);
});
// Starting the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Server is running on port ${PORT}
);
});
To get started...
Create a new directory for your project and navigate into it.
Run npm init -y to initialize a package.json file.
Install Express and body-parser by running npm install express body-parser.
Create a file named app.js or any other name you prefer and paste the above code into it.
Run the server with node app.js.
You can now send GET requests to http://localhost:3000/data to retrieve data and send POST requests to the same URL to add new data.
Make sure to include a JSON body in your POST requests.
Top comments (0)