标头已发送问题

问题描述 投票:0回答:1

我试图使用express的res.download下载文件。文件正在下载,但我不断收到已发送的标头,并且服务器崩溃了

const getRequestTemplate = async (req, res) => {
    try {
        // Call the service function to get the file path
        const filePath = await getRequestTemplateService();
        
        // Send the file as a response
        res.download(filePath, 'requestTemplate.xlsx', (err) => {
            if (err) {
                // Handle errors here
                console.error('Error downloading file:', err);
                res.status(400).json({ statusCode: 400, message: 'Error Downloading Request Template', data: null });
            } else {
                // Send success response if download completes successfully
                console.log('File downloaded successfully');
                // You can send any custom success response here
                res.status(200).json({ statusCode: 200, message: 'Request Template downloaded successfully', data: null });
            }
        });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ statusCode: 500, message: 'Error Downloading Request Template', data: null });
    }
}
node.js express
1个回答
0
投票

当您使用

res.download
express 时,会将文件发送给用户,并且按预期 HTTP 请求将结束,您无法再发送任何响应。但在回调中您试图发送成功响应

res.status(200).json({ statusCode: 200, message: 'Request Template downloaded successfully', data: null });

这会引发错误,因为您无法发送响应,因为它已经由

res.download

发送了

要修复,只需删除成功响应即可

const getRequestTemplate = async (req, res) => {
    try {
        // Call the service function to get the file path
        const filePath = await getRequestTemplateService();
        
        // Send the file as a response
        res.download(filePath, 'requestTemplate.xlsx', (err) => {
            if (err) {
                // Handle errors here
                console.error('Error downloading file:', err);
                
            } else {
                // file sent
                console.log('File downloaded successfully');
            }
        });
    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ statusCode: 500, message: 'Error Downloading Request Template', data: null });
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.