- Create Project Folder: Start by creating a new folder for the project, such as
node-express-server. - Initialize Node.js Project: In the terminal, run
npm init -yto initialize a Node project and create apackage.jsonfile. - Install Express: Run
npm install expressto add Express to the project. - Create
index.jsFile: This will be your main entry point.
- Import Express: In
index.js, import the Express module. - Create Express App: Use
const app = express();to initialize the Express app. - Set Up a Port: Define a constant,
const PORT = 8000;, to store the port number. - Listen on Port: Use
app.listen(PORT, () => {...});to make the server listen on port 8000, logging a confirmation message.
-
Create a Mock Book Array: Define a simple array,
const books = [...], containing sample book objects. Each book should have anid,title, andauthor.const books = [ { id: 1, title: 'Book One', author: 'Author One' }, { id: 2, title: 'Book Two', author: 'Author Two' }, ];
- Define a Route: Use
app.get('/books', (req, res) => {...});to create a route for fetching all books. - Send Book Data: In the route handler, use
res.json(books);to send the entire array of books as JSON.
- Use Path Parameter: Define a route with a path parameter using
app.get('/books/:id', (req, res) => {...});. - Retrieve Book ID: Extract the
idfromreq.params. - Find Book: Use
books.find()to search for the book byid. - Handle Not Found: If no book is found, send a
404response with a relevant message. - Return Book: If the book exists, send it in the response.
- Use Middleware: Add
app.use(express.json());to parse JSON bodies. - Define POST Route: Use
app.post('/books', (req, res) => {...});for adding a new book. - Receive Book Data: Access the new book data from
req.body. - Generate New ID: Set an ID by incrementing the last book’s ID or using a random method.
- Add Book to Array: Push the new book into the
booksarray. - Send Success Response: Respond with the updated book list or a success message.
- Define DELETE Route: Use
app.delete('/books/:id', (req, res) => {...});. - Retrieve Book ID: Extract
idfromreq.params. - Find and Remove Book: Use
books.filter()to exclude the book with the matchingid. - Check Deletion: If no book was deleted, send a
404response. - Send Confirmation: Return a success message indicating the book was deleted, or send the updated book list.
- Start the Server: Run
node index.jsand check for the confirmation message. - Use Postman or cURL: Demonstrate how to test each route using Postman or cURL:
GET /booksGET /books/:idPOST /booksDELETE /books/:id
This step-by-step breakdown will guide your students through setting up and testing a basic Express server with routes for managing a collection of books. Let me know if you'd like to add any advanced steps!