I am using Node.js and ExpressJS to save a mongoose model. I am getting the error of Error: Can't set headers after they are sent.
I think it has to do with the line res.redirect("/dashboard/it/model");
conflicting with setRedirect({auth: '/login'}),
from my route, the code in the setRedirect is below labeled. The setRedirect is from a middleware called middleware-responder
that came as part of the template I am using to create Stripe user accounts. I can not remove it as far as I know. my GitHub repo I have committed all files that are not test files and are relevant (no unneeded views ect than what is already there)
Save Model
if(type=="aps"){
var newAccessPoint = {
name: name,
manufacturer: manufacturer,
model: model,
range: range,
bands: bands,
channel: channel,
poe: poe,
notes: notes,
signout: signout,
author:author
};
// Create a new access point and save to DB
AP.create(newAccessPoint, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to models page
res.redirect("/dashboard/it/model");
}
});
}
Route
app.post('/dashboard/it/model/new',
setRender('dashboard/it/modelCreate'),
setRedirect({auth: '/login'}),
isAuthenticated,
dashboard.getDefault,
(req, res) => {
setRedirect code
exports.setRedirect = function(options){
return function(req, res, next){
if(req.redirect){
req.redirect = _.merge(req.redirect, options);
} else {
req.redirect = options;
}
next();
};
};
setRender code
exports.setRender = function(view){
return function(req, res, next){
req.render = view;
next();
};
};
That's happening because you are trying to send a response to the client when you already closed the connection.
Hard to tell by the way you are showing us your code but it seems like you are redirecting to options and then in the same request you are redirecting to dashboard/it/model
I pull your code from github. I think the error message was clear. in your getDefault()
middleware you are rendering a response so the server start sending data to your client and just after you try to redirect him to another url. Thats why when your comment out that middleware all work nicely.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.