- Fork and clone this repository to your
Development
folder.
Create a middleware that handles requests to non-existing paths.
- Create a middleware method before the
listen
method. - This middleware should end the response with a
404
status code and a message that saysPath Not Found
. - Test your middleware by sending a request to a non-existing path, for example
/whatever
.
Create a middleware that handles all the errors in your application.
- Pass four arguments to your middleware's function:
err
,req
,res
andnext
. - Set the response status to the error object's status. If it doesn't have a status, give it a default status of
500
. - Send an object with the message from the error object as a JSON response. If the error object doesn't have a message, give it the following default message
Internal Server Error
.
- Install morgan
$ npm install morgan
- In
app.js
, create a variable called morgan. - Configure your express application to use morgan using the
dev
format.
- Install cors
$ npm install cors
- In
app.js
, create a variable called cors. - Enable your app to use the cors middleware.
Create a route for the media files.
- Create a folder called
media
for your images. - In
app.js
, create a route with the path/media
. - Join
media
to the directory path__dirname
usingjoin
and pass it toexpress.static
. - Test your route by putting any image in the
media
folder, then in your browser go tolocalhost:8000/media/<image_name>
. - Add
media
to your.gitignore
file.
Set up the upload middleware using multer.
- Install multer
$ npm install multer
-
Create a directory called
middleware
in your root of your application directory, then within themiddleware
folder, create a file calledmulter.js
. -
In this file
multer.js
, copy paste the following code:
const multer = require("multer");
const storage = multer.diskStorage({
destination: "./media",
filename: (req, file, cb) => {
cb(null, `${+new Date()}${file.originalname}`);
},
});
const upload = multer({
storage,
});
module.exports = upload;
- In
posts.routes.js
, require the newly createdmulter
middleware.
const upload = require("../../middleware/multer");
-
Include the
upload
middleware before thepostsCreate
controller route. -
Specify that
single
images are uploaded only and the field name isimage
.
- In
postsCreate
controller method in theposts.controllers.js
, check if an image was uploaded by checking ifreq.file
exists. - If a file is uploaded, save the path in the body as
req.body.image
before the post instance is created. - In the
PostSchema
, add a new property called image of typeString
. - Test your post create api using postman.
- Try to access the image from the post through the browser.
Create a custom middleware when creating a blog that generates a slug for the blog title and adds it to the request.
Use a validation middleware library.
Validate that the title
argument contains letters and not only numbers, and does not exceed 40 character.