下载文件后重定向 - Nodejs

时间:2017-07-28 00:27:19

标签: node.js

我在下载文件后尝试重定向页面。 这是代码:

app.get('/log', function(req,res){
     return res.download('file.txt', function(err){
            if(!err){
                return res.render('index.html');
            }
        });
})

但每次我收到此错误: 错误:发送后无法设置标头。

下载后还有另一种重定向/渲染方式吗? (请在服务器端)。

2 个答案:

答案 0 :(得分:1)

您无法按照您认为的方式执行此操作,因为标头已随下载响应一起发送。

您可以通过自己操纵响应来发送文件下载所需的标题,并同时发送位置标题。请求者应该理解位置标题并相应地重定向。

例如。

const fileData = /* read file */;
res.set({
  'Content-Type': 'text/plain',
  'Location': '/'
});
res.end(fileData);

答案 1 :(得分:1)

只需将位置标题添加到下载响应中:

router.get('/', (req, res, next)=>{
    res.set({
        'Location': "URL://for.redirection"
    });
    res.download("path/to/the/resource");
});
相关问题