Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get authorization header token with node js

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.

like image 467
ahmed Avatar asked Oct 23 '25 09:10

ahmed


1 Answers

Use like this:

req.header('authorization');
like image 118
siva Avatar answered Oct 26 '25 03:10

siva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!