节点JS:res.render()之后res.download()错误 [英] Node JS : Error with res.download() after res.render()
问题描述
我从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屋!