Change headers on ajax.reload() call

Change headers on ajax.reload() call

aumartinezaumartinez Posts: 11Questions: 3Answers: 2
edited December 2022 in Free community support

I have a datatable that uses an authentication header to get data from the API and it works fine, however, the token send in the header has an expiration time, I am capturing the api call error when the token expire but I can't find a way to update the headers options in ajax.reload(), is it possible to modify the headers on ajax.reload() call ?

My implementation is using Datatables with Vue, so I'm not sure how far I can go changing the ajax options object there.

This question has accepted answers - jump to:

Answers

  • aumartinezaumartinez Posts: 11Questions: 3Answers: 2
    edited December 2022

    I have something like this in the ajax object options, I am getting the token from a Vue store:

    let ajax = {
      url: 'API_URL'
      headers: {
        'x-access-token' : login.accessToken
      },
      retries: 1,
      error: function () {
        login.refreshToken()
      }
    }
    

    and have a watcher that on getting a new token it will just run

    let dt = table.value.dt()
    dt.ajax.reload()
    

    it runs the ajax call but loads the previous token and not the new one, resulting on an API error, so I would like to know if could modify the headers on the ajax.reload() call

  • kthorngrenkthorngren Posts: 21,205Questions: 26Answers: 4,926
    Answer ✓

    The ajax docs state this:

    As an object, the ajax object is passed to jQuery.ajax allowing fine control of the Ajax request.

    The jQuery.ajax docs state that the headers option can be a plain object. If you could pass a function then I would say it could be dynamic. I don't believe there is anything in Datatables to dynamically change the value.

    Likely you will need to destroy() the Datatable and reinitialize to pick up the new token value instead of using ajax.reload().

    Kevin

  • aumartinezaumartinez Posts: 11Questions: 3Answers: 2
    edited December 2022

    Tried with beforeSend without luck, will check on your recommendation

  • aumartinezaumartinez Posts: 11Questions: 3Answers: 2
    edited February 2023 Answer ✓

    Just if somebody wonders, yes, beforeSend was the correct approach to overwrite the headers, I was looking to the incorrect function to overwrite the headers, they should be something like:

    beforeSend: function (xhr:any, settings:any) {
        let token = store.getToken()
        xhr.setRequestHeader('x-access-token', token)
      },
    
Sign In or Register to comment.