Search code examples
javascriptheadertokenresponse

Can't get response headers - javascript


I'm creating a site that sends requests to an API server via JavaScript, in one of the requests it requires me to capture a token that is given to create changes to shopping carts, without this token you get a 403 response. The response headers have "access-control-allow-origin: *" which should allow me to get what I need from the headers, but it just wont pass over to my program with headers.get function. Changing the header identifier to use '', lowercase, different uppercase or anything else doesn't create any different results for me in the get function.

this is my code:

const requestUrl = `${url}/carts`;
        // Perform the request
        try {
            let response = await fetch(requestUrl, {
                method: 'POST',
                headers: {
                    'Accept': 'application/vnd.epages.v1+json',
                    'Authorization': at,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(body)

            });
            if (!response.ok) {
                const errorText = await response.text();
                console.error('Error:', response.status, errorText);
            } else {
                const data = await response.json();
                cartToken = response.headers.get("X-ePages-Cart-Token");
                console.log('token: ', cartToken);
                console.log('response data:', data); // Log the parsed data
}

Response headers, as taken from network inspector:

HTTP/2 201 
date: Thu, 22 Aug 2024 12:58:00 GMT
location: https://shop.com/carts/id
x-epages-cart-token: tokenhere
content-type: application/json
x-epages-media-type: application/vnd.epages.v1+json
x-ratelimit-limit: 300
x-ratelimit-remaining: 299
x-ratelimit-reset: 2024-08-22T12:58:30.800Z
access-control-allow-origin: *
vary: Accept-Encoding,User-Agent
content-encoding: gzip
content-length: 1529

Console.log output

This has been written following the API and support guidance, but I can't get the token to pass. Support also made this same request on their side, and was able to get the token, so I'm completely baffled what is wrong on my side.


Solution

  • This ended up being solved by creating a proxy address that makes the initial API call and then forwards the body and headers back to the client using the correct CORS headers.