简体   繁体   English

节点JS:res.render()之后res.download()错误

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

I'm beginning with Node JS, and I get an error : 我从Node JS开始,但出现错误:

Error: Can't set headers after they are sent. 错误:发送标头后无法设置标头。

You can see my code, the problem is with res.download() ; 您可以看到我的代码,问题出在res.download() Or, how can I show the view without res.render() ? 或者,如何在没有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');
  });
})

You are sending res.download after res.render . 您要在res.download之后发送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. 这就是导致错误的原因。 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) 您需要做的是先render视图(您可以发送get请求以渲染视图),然后在加载该视图时,调用another route download文件(发送post路径以下载)

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');
    }); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM