Agenda
<aside> 📌 Reminders
<aside> 💡
Node.js: a runtime environment for executing JavaScript code outside of the browser. It allows you to build server-side applications with JavaScript.
</aside>
<aside> 💡
npm: the default package manager for Node.js. You'll use it to manage project dependencies like Express, Mocha, and Chai.
</aside>
# Initialize the project and create a package.json file
$ npm init
# Install Express.js
$ npm install --save express
# Install development dependencies like Mocha, Chai, and Chai-HTTP for testing
$ npm install --save-dev mocha chai chai-http
<aside> 💡
Express.js: a minimal and flexible Node.js framework used for building web applications and APIs. It simplifies HTTP request handling, routing, and middleware integration.
</aside>
// Import the express package
const express = require('express');
// Create an instance of Express
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
// Define a sample GET route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server running on <http://localhost:3000>');
});
<aside> 💡
REST (Representational State Transfer): an architectural style for designing networked applications. In RESTful APIs, resources (like messages) are identified via URLs, and actions are performed using HTTP methods (like GET, POST, DELETE).
</aside>
// Define an array to store messages
let messages = [];
// POST request to create a new message
app.post('/api/messages', (req, res) => {
const newMessage = {
id: messages.length + 1,
content: req.body.content,
author: req.body.author,
upvote: 0,
downvote: 0
};
messages.push(newMessage);
res.status(201).json(newMessage);
});
// GET request to fetch all messages
app.get('/api/messages', (req, res) => {
res.json({ messages });
});
// DELETE request to remove a specific message by ID
app.delete('/api/messages/:id', (req, res) => {
const messageId = parseInt(req.params.id);
messages = messages.filter(msg => msg.id !== messageId);
res.json({ messageId, status: 'deleted' });
});