简体   繁体   中英

How to send api token for each user in ajax header?

In Laravel project, I get my api token from database and use it in ajax header in local environment. know I want to set api token in header for each user. How can I do this?

Here is my ajax:

<script>
 $.ajax({
                url: url,
                headers: {"Authorization": "Bearer my_token "},
                type: 'GET',
                data: data,
                success: function( data){
                    console.log(data)
                }
            });
 </script>

Now I want to send each use token with header not just for one person.

save it in local storage when you login or sign up like this:

localStorage.setItem('token',your_token)

and when you need to send it just make this line like this:

headers: {"Authorization": "Bearer "+localStorage.getItem('token')},

Try it.

$.ajax({
    url: url,
    headers: {
        'Authorization': `Bearer ${token}`,
    },
    method: 'POST',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

I am not sure what you meant by "Now I want to send each use token with header not just for one person." But if you are referring sending token with every ajax request, You can do it by adding the script below, It's similar to Laravel X-CSRF-TOKEN setup this is just one-time setup. With every ajax request it will automatically add the token.

$.ajaxSetup({
    headers: {
        'Authorization': "Bearer "+localStorage.getItem('token'),
    }
    });

Finally, I put this in meta tag:

<meta meta name="api_token" content="{{ (Auth::user()) ? Auth::user()- 
>api_token : '' }}">

And in script part:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        'Authorization': 'Bearer ' + $('meta[name="api_token"]').attr('content'),
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM