A
A
Artem Komarov2014-02-17 16:00:42
Computer networks
Artem Komarov, 2014-02-17 16:00:42

Node.js express.js: how to make redirect friends with cookies so that both cookies are set and the redirect occurs?

The bottom line is: I'm making an application that receives authorization data through another web server
and sets the client's cookies received from it. Here is a piece of code:

var params = null, response = res, query = require('url').parse(req.url,true).query,
    qs = require('querystring');
  var options = {
    host: outhost,
    port: 8080,
    path: '/auth?action=logon&'+qs.stringify({login:query.login},{password:query.password}),
    method: 'GET'
  };
  http.get(options, function(res) {
    res.setEncoding('utf8');
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
  });.on('data', function (chunk) {
    console.log(chunk.toString());
    params = JSON.parse(chunk);
    response.cookie('ssid', params.ssid).cookie('sessionurl', params.sessionurl);
  });.on('end', function () {
    response.redirect('/index');
    });

The server crashes with an error:
Can't set headers after they are sent

Of course, I understand that the redirect is prescribed through the header, but why is it so with cookies? CHADNT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
quex, 2014-02-17
@m0sk1t

cookies are also placed through headers :)
you have an error in the on('data', ... ) handler. the name of the chunk variable should have hinted at this. when data is received, the data event occurs repeatedly - the data does not arrive immediately, but in pieces, each piece is a chunk. you first need to collect these pieces, and then manipulate them.

...
var buffer = '';
...
http.get(options).on('data', function(chunk){
    buffer += chunk.toString();
}).on('end',function(){
     params = JSON.parse(buffer);
     response.cookie('ssid', params.ssid).cookie('sessionurl', params.sessionurl);
     response.redirect('/index');
});

something like this.
In general, for some reason it seems to me that if the Set-cookie and Location headers are set at the same time, Set-cookie will be ignored, but I'm not sure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question