节点JS:res.render()之后res.download()错误 [英] Node JS : Error with res.download() after res.render()

查看:96
本文介绍了节点JS:res.render()之后res.download()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Node JS开始,但出现错误:

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


错误:发送标头后无法设置标头。

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

您可以看到我的代码,问题出在 res.download();
或者,如何显示没有 res.render()的视图?

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


推荐答案

您要在之后发送 res.download res.render 。这将尝试再次发送响应,但是您不能两次发送响应。这就是导致错误的原因错误:发送标头后无法设置标头。

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.

您需要的首先要做的是渲染视图(您可以发送 get 请求来渲染视图),加载后,调用另一条路径来下载文件(发送 post 下载路径)

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

这篇关于节点JS:res.render()之后res.download()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆