Node JS : Error with res.download() after res.render()

徘徊边缘 提交于 2019-12-11 06:19:09

问题


I'm beginning with Node JS, and I get an error :

Error: Can't set headers after they are sent.

You can see my code, the problem is with res.download(); Or, how can I show the view without res.render()?

Can you tell me how to fix this issue? Thanks you!

var express = require('express');
var app = express();
var pythonShell = require('python-shell');

app.set('view engine', 'ejs');
app.use(express.static('style'));

app.post('/downloads', function(req, res) {                                 
  res.render('downloads.ejs');
  console.log("Python script begins");
  pythonShell.run('./generator.py', function (err) {
    if (err) throw err;
    console.log("Python Script Ended");
    res.download('mapCreated.tiff', 'map.tiff');
  });
})

回答1:


You are sending res.download after res.render. this will try to send the response again, but you can't send response two times. That is what is causing the error Error: Can't set headers after they are sent.

What you need to do is render the view first( you can send a get request to render the view) and when that view is loaded, call another route to download the file( send post route to download)

app.get('/downloads', function(req, res) { 
    res.render('downloads.ejs');
});

app.post('/downloads', function (req,res){
    console.log("Python script begins");
    pythonShell.run('./generator.py', function (err) { 
        if (err) throw err; 
        console.log("Python Script Ended");
        res.download('mapCreated.tiff', 'map.tiff');
    }); 
})


来源:https://stackoverflow.com/questions/47057761/node-js-error-with-res-download-after-res-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!