简体   繁体   中英

getJSON & Bearer token

I have a working getJSON script to output the JSON strings. But with a Bearer Token api it dosnt work.

In my Http Header is allready included.. authorization: Bearer Mytoken

does anyone have an idea for me?

    <div id = "stage" style = "background-color:#cc0;">
         STAGE
      </div>

      <input type = "button" id = "driver" value = "Load Data" />

<script>
         $(document).ready(function() {

            $("#driver").click(function(event){
               $.getJSON('https://www.myapiwithbtoken.com/result.json', function(jd) {
                  $('#stage').html('<p> Name: ' + jd.name + '</p>');
                  $('#stage').append('<p>Age : ' + jd.age+ '</p>');
                  $('#stage').append('<p> M: ' + jd.m+ '</p>');
               });
            });

         });
      </script>

You are going to want to use another method to attach the bearer token to your headers when you make the request. With the code you provided, it doesn't seem like it would do so. Look at the $.ajax method, below is an example of making a GET request.

You can see that you get a "done" and "fail" callback method to work with...

$.ajax({
    type: "GET", //GET, POST, PUT
    url: '/authenticatedService'  //the url to call
    contentType: contentType,           
    beforeSend: function (xhr) {   //Set token here
        xhr.setRequestHeader("Authorization", 'Bearer '+ token);
    }
}).done(function (response) {
    //Response ok. Work with the data returned
         $('#stage').html('<p> Name: ' + response.name + '</p>');
         $('#stage').append('<p>Age : ' + response.age+ '</p>');
         $('#stage').append('<p> M: ' + response.m+ '</p>');

}).fail(function (err)  {
    //Handle errors here
         $('#stage').append('<p>error with fetching results</p>');
});

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