Answer the question
In order to leave comments, you need to log in
What is the problem in express framework Error: Can't set headers after they are sent?
Hello, an error occurs when trying to form a request to vk api and issue a text file for download. As you can see, the file is rendered directly from the data acquisition function, which of course is wrong in terms of code organization, but at that time I just came up with it. An important note - the error occurs when you re-access the
index.js url
...
var vk = require('./lib/vk.js');
...
app.get('/vk', function(req, res) {
if(req.query.action === 'getwall') {
vk.getMessages('wall.get', {'owner_id' : req.query.id},res);
} else {
res.render('home', {view:'vk'});
}
});
exports.getMessages = function (req, params, res) {
vk.setSecureRequests(true);
vk.request(req, params);
vk.on('done:wall.get', function (_o) {
if(_o) {
res.set({"Content-Disposition":"attachment; filename=\"backup.txt\""});
res.send(JSON.stringify(_o, null, 4));
//res.render('home', {vk: JSON.stringify(_o, null, 4)});
}
});
};
5|index | Error: Can't set headers after they are sent.
5|index | at ServerResponse.setHeader (_http_outgoing.js:358:11)
5|index | at ServerResponse.header (/../vk/node _modules/express/lib/response.js:719:10)
5|index | at ServerResponse.header (../vk/node _modules/express/lib/response.js:722:12)
5|index | at VK.<anonymous> (/.../vk/lib/vk.js:1 5:6)
5|index | at emitOne (events.js:101:20)
5|index | at VK.emit (events.js:188:7)
5|index | at IncomingMessage.<anonymous> (/.../v k/node_modules/vksdk/sdk.js:307:31)
5|index | at emitNone (events.js:91:20)
5|index | at IncomingMessage.emit (events.js:185:7)
5|index | at endReadableNT (_stream_readable.js:974:12)
app.get('/getwall/:action?/:id?',vk.getWall, function(req, res) {
res.render('home', {view:'vk'});
});
exports.getWall = function (req, res, next) {
if(req.query.id)
vk.setSecureRequests(true);
vk.request('wall.get',{'owner_id' : req.query.id});
vk.on('done:wall.get', function (_o) {
console.log(req.query.id);
if(_o) {
req.wall = {vk: JSON.stringify(_o, null, 4)};
next();
}
});
};
Answer the question
In order to leave comments, you need to log in
If you do something res.send[.render, .end, etc.], then you don't need to send anything after, otherwise this error will occur.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question