Search code examples
javascriptreactjshttp-headerscorsbluesnap

Can't accses fetch() response location header in JS


I'm having a problem that already disccussed here at stackoverflow and at other platforms (1,2), but the solution that was offered is not possible in my case.

I'm trying to get a Token from BlueSnap (payment proccesing company, details about the exact action can be found here) via POST request and fetch(). the request is working, and the Token is being sended to me via the Location header in the response. I can see the header and the desired token via Chrome dev tools, but I can't get and use it on my JS code. The response.headers object is empty, and any way I tried to accses response.header.Location failed.

I tried This:

console.log(response.headers.get('location'))

And also this

for(const header of response.headers){
  console.log(header);
}

but none of this seems to work.

As disscused here I tried to add this:

'Access-Control-Expose-Headers': 'location'

to my list of headers in the request so it fits CORS policy requiremnts, but it didn't help. I think this should be inserted in the server side, and not in the client. My guess is that I`m not the first to enconuter this issue, but the customer suppurt of BlueSnap doesn't have a solution for this. Is the only possible solution is to add the 'Access-Control-Expose-Headers': 'location' on there servers?

My question is this: How can i accses this http response Location header, which is defenatly sent to my browser, but can't be used at the moment with my JS code.

Thanks a lot for your time and effort!

*I dont think i matter for this specific issue, but I'm working on this project with ReactJS


Solution

  • You can't.

    The APIs for making HTTP requests from JavaScript in a web browser (fetch and XMLHttpRequest) follow redirects transparently.

    The response object will contain the response for the request to the location specified in the location header. You never get access to the response containing the redirect instruction.


    If you read the documentation for the API, it says:

    You create a Hosted Payment Fields token for the specific checkout session, using a server-to-server API call.

    … so you shouldn't be accessing that from client-side JS in the first place.