I have this login code for my node http server request to do a simple login:
if (request.method === 'POST' && request.url.endsWith('login'))
{
request.on('data', function(data) {
var credentials = JSON.parse(data);
if (credentials && credentials.name === 'test' && credentials.password === 'letmein')
{
// ok, new login
securityCookieValue = guid();
response.setHeader('Set-Cookie', 'JSESSIONID=' + securityCookieValue);
response.statusCode = 200;
response.end();
return;
}
else
{
// request new login
response.statusCode = 401;
response.end();
return;
}
});
}
This gives me a Can't set headers after they are sent
error. http request with node.js fail Can\'t set headers after they are sent does sufficently explain why this happens: The function passed to request.on
is handled after the headers are sent.
How can I avoid this. I need to read and parse the data of the POST request before I can set the cookie.