gpt4 book ai didi

javascript - 异步代码设计错误。未处理的PromiseRejection警告: Error [ERR_HTTP_HEADERS_SENT],

转载 作者:行者123 更新时间:2023-12-03 07:06:52 24 4
gpt4 key购买 nike

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

输出:容器成功

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

错误:( Node :18364)UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置 header

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

DeprecationWarning:未处理的 promise 拒绝已被弃用。将来,未处理的 Promise 拒绝将会以非零退出代码终止 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,因为一个请求只有一个响应。我假设您想要发送“两部分”响应,以便用户首先看到“容器中成功”,然后(几秒钟后)“上传成功...”。

如果您使用,Node.js 将以两个“ block ”发送响应

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

(另请参阅 this answer 中的说明。)

关于javascript - 异步代码设计错误。未处理的PromiseRejection警告: Error [ERR_HTTP_HEADERS_SENT],,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71276446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com