get authorization header token with node js

21,381

Use like this:

req.header('authorization');
Share:
21,381
ahmed
Author by

ahmed

Updated on January 27, 2020

Comments

  • ahmed
    ahmed over 4 years

    I would like to get token in backend node js.

    First, I get the token from jwt and I stored in localstorage,but when i would like to send a request with this token, I can't get it in server side.

    Client side:

            function list_users(){
                url= "http://localhost:8181/users";
                var tok = window.localStorage.getItem('token');
                if (tok) {
            /*
            $.ajaxSetup({
                        headers: {
                            'x-access-token': tok
                        }
                    });
            */
    
                    $.ajax({
                    headers: {'Authorization': tok},
                    dataType: "application/json; charset=utf-8",
                    url,
                    type: 'GET',
                    dataType: 'json',
                    success: function (json) {
        alert("done");
        }
    })
    }
    }
    

    Server side:

    router.use(function(req, res, next) {
    
    res.header("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  
    res.header("Access-Control-Allow-Headers", "Authorization");
    
    console.log(req.headers['authorization']);
    ...
    
    }
    

    But

    req.headers['authorization']

    print

    "undefined"

    Any solution please.

    • cassiomolin
      cassiomolin almost 7 years
      Have you inspected the request to confirm if the token has been sent to the server?
    • ahmed
      ahmed almost 7 years
      no, not yet, how can I do it ?
    • cassiomolin
      cassiomolin almost 7 years
    • ahmed
      ahmed almost 7 years
      @CássioMazzochiMolin, no the request don't send the token to the server but the request headers is set as "Authorization". take a look in this link