Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can’t access cross-origin response header from frontend JavaScript

I am building a simple web app using ReactJS and create-react-app.

I have a backend API set up on Heroku where I can make POST requests. Everything works fine, except:

When I make a POST request using fetch API, the response is 100% correct but it only gives me 2 standard headers. I want to get my custom header. I have added expose header in my response and here's the plot twist: When I view the headers from Chrome Inspection Tool or Postman (API tool), it shows all the headers, including my custom one. Here is the fetch code I'm using -

fetch(theUrl, {
  method: 'POST',
  body: JSON.stringify({
    "placeholder": "placeholder"
  })
})
.then(function(res) {
  console.log(res.headers.get('CUSTOM_HEADER_NAME'));
})

If it makes any difference, this fetch method is called from a function outside the main body of the ReactJS component.

The name of the custom header is Image-Identification-Path, and the header in my response header is Access-Control-Expose-Headers for Image-Identification-Path.Here's the image from Postman

Summary: How do I get my custom header using fetch?

like image 564
Fahmid Avatar asked Dec 23 '22 19:12

Fahmid


1 Answers

You must configure the server to which the request is sent, such that its response has an Access-Control-Expose-Headers header that has the name of your custom response header.

Otherwise, if your browser doesn’t see the name of your custom header in that Access-Control-Expose-Headers header, it won’t let you access the value of your custom header.

In such a case it’s expected that you’d still be able to see the custom header if you look at the response in Postman or even in your browser devtools.

But just because the browser gets the custom header in the response doesn’t mean the browser will expose it to your frontend JavaScript code.

For cross-origin requests, browsers will only expose that custom response header to your frontend code if that header name is in the Access-Control-Expose-Headers value.

like image 95
sideshowbarker Avatar answered Dec 31 '22 01:12

sideshowbarker