Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set token value in response header using express.js

I am having trouble setting token into header. I read express.js 4 doc at

http://expressjs.com/4x/api.html#res.set

and it stated like

res.set('token', 'kjhdkf89q37453lajjfq23');

Below are how I configure express.js

var restful_express = express(); restful_express.use(bodyParser());

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST');
    next();
}

restful_express.use(allowCrossDomain);

restful_express.listen(7788, function() {

});

How I sent response back

res.set('token', 'kjhdkf89q37453lajjfq23');

res.json({userid:"123123678"});

and when I retrieve using jQuery and the value I got are below:

$.post( $('#url').val() + "/login", {email:"[email protected]"}).done(function( data, textStatus, request ) {

    console.log(data.userid);
    // 123123678

    console.log(textStatus);
    // success

    console.log(request.getAllResponseHeaders()); 
    // Content-Type: application/json 

    console.log(request.getResponseHeader("token")); 
    // null

});

Appreciate any advice please. Thanks !

regards, Mark

like image 494
Mark Thien Avatar asked May 25 '26 09:05

Mark Thien


1 Answers

For CORS, you need to also set Access-Control-Expose-Headers to let the browser know which custom headers it is allowed to access.

like image 102
mscdex Avatar answered May 27 '26 16:05

mscdex