uploading files with multer after user is authenticated

Viewed 939

using multer, I can successfully upload any type of file to my node.js backend from my reactjs client and I can create a user as well. Now I am trying to figure out a way to only allow authenticated users to upload files. Does anyone know of any resources that can help me figure out what I need to do?

3 Answers

you can use any authentication middleware on your upload route. for example.

 const upload = multer({ dest: 'uploads/' })

   const authentication = function (req, res, next) {
   // handle authentication
    if(authenticated) return next()
    next({error})
   })


   app.post('/profile', authentication, upload.single('avatar'),
   function (req, res, next) {

   })

this will authenticate requests before multer handles the request

For those not getting the req.body, you can pass your tokens with the Headers like so

const options = {
    headers: {'jwt': sessionStorage.getItem("token")}
};

and for the request

axios.post("http://xxx", your data, options)

Use a mongodb database to authenticate users.

Related