Reputation: 79
C:\Users\jsj10\node_modules\mysql\lib\protocol\Parser.js:80
throw err; // Rethrow non-MySQL errors
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:\Users\jsj10\node_modules\express\lib\response.js:767:10)
at ServerResponse.append (C:\Users\jsj10\node_modules\express\lib\response.js:728:15)
at ServerResponse.res.cookie (C:\Users\jsj10\node_modules\express\lib\response.js:853:8)
at ServerResponse.clearCookie (C:\Users\jsj10\node_modules\express\lib\response.js:800:15)
at Query.<anonymous> (C:\Users\jsj10\Desktop\TravelA\server.js:177:18)
at Query.<anonymous> (C:\Users\jsj10\node_modules\mysql\lib\Connection.js:502:10)
at Query._callback (C:\Users\jsj10\node_modules\mysql\lib\Connection.js:468:16)
at Query.Sequence.end (C:\Users\jsj10\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
Program node server.js exited with code 1
This is my error. I can't find what's problem although I looked so many questions. Please help me what's the problem. I think all of my code isn't wrong at all. Tell me where should I fix. Down is my code.
app.post('/writing_server',function(req,res){
var title = req.body.writing_title;
var author = req.body.author;
var contents = req.body.contents;
var user_id = req.body.user_id;
var sql = "insert into "+before_page+"(title,author,content,user_id) values(?,?,?,?)";
if(user_info.id != 'admin' && author.toLowerCase() === 'admin'){
write_message = "You can't use admin NickName!";
res.redirect('/write?before='+before_page);
}
else {
conn.query(sql,[title,author,contents,user_info.id],function(err,rows,fields){
if(err) console.log(err);
else {
res.redirect('/menu/'+before_page);
res.clearCookie('before_page');
}
});
}
})
Upvotes: 1
Views: 487
Reputation: 3965
In Express, the response
(or res
) parameter of the callback of a routing method (app.get()
, app.post()
, etc.) has methods that send data back to the client (such as res.redirect()
) and methods that set header data before a method like res.redirect()
is called.
In your code, you are trying to do this:
res.redirect('/menu/'+before_page);
res.clearCookie('before_page');
But it should be the other way around:
res.clearCookie('before_page');
res.redirect('/menu/'+before_page);
The res.clearCookie()
method sets header data for res.redirect()
to make use of, so these methods have to be called in this order.
Upvotes: 1
Reputation: 20155
Put these two lines in the following order
res.clearCookie('before_page');
res.redirect('/menu/'+before_page);
You can check whether an operation sends headers to the client or not with
console.log(res.headersSent)
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections
Upvotes: 0