There is a JWT token, the documentation says ( https://jwt.io/introduction/ ) that for authorization you need to send

Authorization: Bearer <token> 

in the form of an authorization header, but where to send and in what way? And what is the authorization header and how to work with it on js?

    1 answer 1

    Add to request headers

     var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; var url = 'https://exemple.com'; 

    fetch

     fetch(url, { method: 'POST', headers: new Headers({ 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }), body: { /* some data */ } }); 

    XMLHttpRequest

     var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(/* some data */); 

    jQuery

     $.ajax({ type: 'POST', url: url data: { /* some data */ }, contentType: 'application/json', beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", 'Bearer '+ token); } }); 
    • Thanks, does this work with the usual jquery ajax? - aSpectro
    • @aSpectro yes of course, ajax from jQuery under the hood uses XMLHttpRequest, now I’ve added as an example - Alexander Zaytsev
    • thanks for the reply - aSpectro
    • The headers seem to be sent, but I get the error "response for preflight does not have http status" as I understand it is due to the cross-origin, do not tell me this is a problem on the client or on the server? - aSpectro
    • @aSpectro is a browser that sends an OPTIONS request to the server, and the server must confirm from which domains it can accept requests. I have very superficial knowledge of the back, you can first allow everyone to add Access-Control-Allow-Origin: * to the response headers Access-Control-Allow-Origin: * - Alexander Zaytsev