Untitled
unknown
plain_text
10 months ago
1.8 kB
6
Indexable
const express = require('express');
const Book = require('../models/book');
const router = express.Router();
router.post('/api/books', async (req, res) => {
try {
const book = new Book(req.body);
const savedBook = await book.save();
res.status(201).json(savedBook);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
router.get('/api/books', async (req, res) => {
try {
const books = await Book.find();
res.status(200).json(books);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
router.get('/api/books/:id', async (req, res) => {
try {
const book = await Book.findById({_id:req.params.id});
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.status(200).json(book);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
router.put('/api/books/:id', async (req, res) => {
try {
const updatedBook = await Book.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true, runValidators: true }
);
if (!updatedBook) {
return res.status(404).json({ message: 'Book not found' });
}
res.status(200).json(updatedBook);
} catch (error) {
res.status(500).json({ message: error.message });
}
});
router.delete('/api/books/:id', async (req, res) => {
try {
const book = await Book.findByIdAndDelete(req.params.id);
if (!book) {
return res.status(404).json({ message: 'Book not found' });
}
res.status(200).res.status(200).redirect("delete.html");
} catch (error) {
res.status(500).json({ message: error.message });
}
});
module.exports = router;Editor is loading...
Leave a Comment