[Vuejs]-Node.js : How to use token with multer?

0👍

Function verifyToken in router('/fromOther') checks just req.headers["authorization"], so I just added the function verifyToken to both router as argument(in fact don’t need to add verifyToken to router('/toOther') but wanted to make it safer) and added the key "authorization" and the value as req.headers.authorization to router('/toOther'). Then it worked well, but I don’t know this will be safe enough.

//(...)
router.post('/fromOther', verifyToken, uploadForSentFile.single('logo'), function (req, res) {
  
  console.log("------file upload -------")
  console.log(req.file)
  res.json(req.file)

});

router.post('/toOther', verifyToken, uploadForSentFile.single('logo') , async function (req, res) {
  let formData = new FormData()

  formData.append('logo', fs.createReadStream(req.file.path), { knownLength: req.file.size })
  
  const headers = {
      ...formData.getHeaders(),
      "Content-Length": formData.getLengthSync(),
      "authorization": req.headers.authorization
  };
  
  try {
    let result = await axios.post(
      new URL('/file/fromOther', req.body.serverURL).href,
      formData,
      {headers }
    )
    
    res.status(200).json(result.data)
  } catch (err) {
    console.log('file/toOther err', err)
  }
})
//(...)

Leave a comment