get authorization header token with node js

2019-08-17 08:54发布

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.

1条回答
Ridiculous、
2楼-- · 2019-08-17 09:35

Try something like this:

.....
.....

$.ajax({
         headers: {'Authorization': 'Bearer '+tok},
......
......
查看更多
登录 后发表回答