bbc / tal

TV Application Layer
http://bbc.github.com/tal
Other
561 stars 149 forks source link

How to Add Custom Headers ? #468

Closed Himanshu-Gurung closed 6 years ago

Himanshu-Gurung commented 6 years ago

Hello All,

I came across an issue regarding the header includes in the GET/POST request. I have a custom header enabled from backend as x-access-token. How can I implement that onto header?

I tried to experiment with the help of the guidelines, using executeCrossDomainGet method. But the header param we have is just the bearerToken.

Thanks In Advance, Himanshu

subsidel commented 6 years ago

Since the implementation of executeCrossDomainGet will use a JSON with Padding method when the device configuration is set such that it doesn't implement CORS fully/correctly, it is limited in what it can support to what is possible with a <script> so as not to have inconsistent behaviour on different devices.

If the request is to the same domain as the application is running on, you will be able to pass in headers to the loadURL opts param. eg.

device.loadUrl('https://www.example.com/api', {
  method: 'GET' // or 'POST' etc
  headers: {
    'x-access-token': 'abcdef1234567890'
  }
})

If this does have to be Cross Origin, and the devices set you are targeting all implement CORS correctly, you can use XMLHttpRequest directly. And on some newer devices you may even be able to use fetch, or at least be able to polyfill in fetch with something like github/fetch (most after 2013/2014 in my experience) though you will need to verify this on the devices you are targeting.

Himanshu-Gurung commented 6 years ago

Thank you for your response @subsidel . But I still not able to work, I am accessing the cross domain get request and following are codes implemented: device.loadUrl(url, { method: 'GET', headers: { 'x-access-token': 'sdgfhf' }, onLoad: function (response){ cb.onSuccess(JSON.parse(response).results); }, onError: cb.onError });

Earlier I was using XMLHttpRequest, but tried to follow BBC guidelines being afraid that XMLHttpRequest will not work for the TVs.

Will be eagerly waiting for your reply.

subsidel commented 6 years ago

If the device you are targeting doesn't implement CORS and the request you must make is to a different origin, then I'm afraid TAL cannot help as you cannot add custom headers to a <script>

If the device doesn't support XMLHttpRequest, then it will not be possible at all to make such a request at all, same origin or different - though I don't believe that TAL supports any devices that don't work with XMLHttpRequest for same origin requests, so this should work.

Are you getting any errors in your browser console/ network responses?

Himanshu-Gurung commented 6 years ago

Thank you for the update @subsidel. No console error/network responses at the moment. I guess I to go with the XMLHttpRequest, hope it works with all the TV devices.