0

I have the following CURL request requiring a JWT token for accessing a protected route in express.js. This request is working fine.

curl --request GET \
  --url http://localhost:3001/api/v1/protected/random-quote \
  --header 'Authorization: Bearer eyJ0xxxxQ.NLNOn1caBeGFlPRnsSjLDIKFggMItcm-dl5PKOjlLxs' \
  --header 'Content-Type: application/json'

How do I formulate the corresponding AJAX request?

<script>
var id_tok = Cookies.get('id_token');
var access_tok =   Cookies.get('access_token');

var headersOb = 'Authorization: Bearer ' + access_tok;

$.ajax({
  type: 'GET',
  url:   'http://localhost:3001/api/v1/protected/random-quote',
 headers: headersOb,
 contentType: 'application/json',
 dataType: 'json'
}).done(function(data) {
 console.log(data);
 console.log('data called success');
});
</script>

With the above AJAX request I get the following error:

VM9599 jquery.min.js:3049 GET   http://localhost:3001/api/v1/protected/random-quote 401 (Unauthorized)
codebird456
  • 505
  • 8
  • 19
  • 3
    I think `headersOb` should actually be an object: `{"Authorization": "Bearer ..."}`. Check in DevTools "network" whether the request includes your custom header. – Tobias K. Aug 08 '18 at 14:52

1 Answers1

1

Need to pass an object to headers option

headers: {'Authorization': 'Bearer ' + access_tok}
charlietfl
  • 170,828
  • 13
  • 121
  • 150