异步代码设计错误。 UnhandledPromiseRejectionWarning: 错误 [ERR_HTTP_HEADERS_SENT],

Error with async code design. UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT],

我遇到 node/express 的错误。我假设问题出在我的异步代码设计上。

输出: 容器成功

预期输出: 容器的成功.. 上传成功...

错误:(节点:18364)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:发送给客户端后无法设置headers

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或者拒绝未使用 .catch()

处理的承诺

弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将以 non-zero 退出代码终止 Node.js 进程。

代码:

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;

每个请求不能多次使用 res.send,因为一个请求只有一个响应。我假设您想发送一个“two-part”响应,以便用户首先看到“容器中成功”,然后(几秒后)“上传成功...”。

如果您使用

Node.js 将以两个“块”发送响应

res.write("Success in container");
...
res.end("Success in Uploading...");

(另请参阅 中的说明。)