I am facing an error with node/express. I am assuming the issue is with my asynchronous code design.
Output:
Success in container
Expected Output:
Success in container..
Success in Uploading…
Error: (node:18364) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Code:
const express = require("express");
const multer = require("multer");
const AuthReq = require("../middleWare/AuthReq");
require("dotenv").config();
const Azure_Storage_Connection_String = process.env.Azure_Connection_String;
const { BlobServiceClient } = require("@azure/storage-blob");
const Router = express.Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage: storage });
Router.post("/profile", AuthReq, upload.single("profile"), async (req, res) => {
const file = req.file;
const blobServiceClient = BlobServiceClient.fromConnectionString(
Azure_Storage_Connection_String
);
const containerName = req.user._id;
const ContainerClient = blobServiceClient.getContainerClient(containerName);
try {
const containerResponse = await ContainerClient.create();
} catch (err) {
return res.status(400).send("Error while sending image");
}
res.send("Success in container");
const contentType = file.mimetype;
const filePath = file.path;
const blobName = file.filename + contentType;
const blockBlobClient = ContainerClient.getBlockBlobClient(blobName);
try {
const uploadBlobResponse = await blockBlobClient.uploadFile(filePath);
} catch (err) {
return res.status(400).send("Error while sending image");
}
res.send("Success in Uploading...");
});
module.exports = Router;