Set up express middlewares inside the server.js
to receive body data
app.use(express.json());
Set up error handler for the post route
const createQuote = (req, res) => {
if (!req.body) {
res.status(400);
throw new Error("Please add a quote and author field");
}
res.status(200).json({ message: "Create quote" });
};
Set up error handler for the update route
const updateQuote = (req, res) => {
if (!goal) {
res.status(400);
throw new Error("Goal not found");
}
res.status(200).json({ message: `Update quote, ${req.params.id}` });
};
Set up error handler for the delete route
const deleteQuote = (req, res) => {
if (!goal) {
res.status(400);
throw new Error("Goal not found");
}
res.status(200).json({ message: `Delete quote, ${req.params.id}` });
};
Change the default express error by adding error handler middleware in an errorMiddleware.js
file inside a middleware folder to be created
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
You might need this later
module.exports = {
errorHandler,
};
Bring in the error handler middleware into server.js
and use it
const { errorHandler } = require("./middleware/errorMiddleware");
app.use(errorHandler);
Test the post route to make sure the error handler is working by inputting no data to the body