2

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.

Community
  • 1
  • 1
BetaRide
  • 16,207
  • 29
  • 99
  • 177
  • 1
    It most likely isn't something to do with this particular bit of code, but something else outside of the `if` clause. What happens if you create an endpoint with just this code, does it work then? – Schlaus Jun 10 '16 at 12:25

1 Answers1

0

response.statusCode must be before response.setHeader

adam-beck
  • 5,659
  • 5
  • 20
  • 34
  • It's complaining alreday on `response.setHeader` line. I tried anyway but it did not help. – BetaRide Jun 10 '16 at 12:30
  • I was basing that suggestion off of http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent but I don't think it matters. I created a test sample and it seems to be working no matter the order I use. – adam-beck Jun 10 '16 at 12:48