简体   繁体   中英

How to set cookie header after processing post data in node.js

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.

response.statusCode必须 response.setHeader 之前

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM