Creating REST APIs with JavaScript can be accomplished using various frameworks and libraries. Below is a basic example of how to create a simple REST API using Node.js with the Express framework:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
// Sample data
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' }
];
// GET all users
app.get('/users', (req, res) => {
res.json(users);
});
// GET a single user by ID
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// POST a new user
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?