skip to Main Content

I have a code so as to upload some images in Node.js. In this code, I’m using the "multer" module for the purpose of image uploading. But I want to ensure that the token of the user is verified before he or she can upload any image to my server. How can I do this?

Here’s my full code:

const express = require("express");
const multer = require("multer");
require("dotenv").config();

const app = express();
const router = express.Router();

app.use(router);

process.on("uncaughtException", (err) => console.error(err));

const storage = multer.createDiskStorage({
    destination: (req, file, cb) => cb(null, "uploads"),
    filename: (req, file, cb) => cb(null, Math.floor(Date.now() / 1000) + file.originalname)
});

const upload = multer({ storage: storage });

router.post("/upload-image", upload.single("image"), async (req, res, next) => {
    if (req.file) {
        res.status(200).json({ status: "OK", file_name: req.file.originalname });
        return next();
    }
    else return res.status(400).json({ status: "Bad Request" });
});

app.listen(process.env.CLOUD_SERVER_PORT, process.env.CLOUD_SERVER_IP_ADDRESS, () => console.log("Cloud server is running..."));

2

Answers


  1. You can manage token verification in the "filename" section.

    Login or Signup to reply.
  2. You can add a middleware to handle this authorization/authentication. Plus it is a good practice to separate this process from the actual business logic, and gives you the ability to extend this verification and use it with other routes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search