Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing headers in Fetch response

I need to make a CORS post request. I need to use fetch because axios's response is already processed to json.

But in fetch response, the headers is empty. But I don't think this is the server problem since axios response headers have the values that I want.

Any trick?

    fetch('http://localhost:9876/test/sample-download', {         method: 'post',         headers: {},         body: {}     })         .then(response => {             console.log(response);         })         .catch(err => console.error(err));      axios.post('http://localhost:9876/test/sample-download', {}, {})         .then(response => console.log(response))         .catch(error => console.error(error)); 
like image 459
william Avatar asked Jan 24 '18 00:01

william


People also ask

How do I add a header to API response?

Adding Custom Header for Individual Response We create a very basic HTTP GET endpoint. Within this endpoint, we access the Response object through the HttpContext object. Then, we add a new header, with the name of x-my-custom-header and a value of individual response .

What is headers in Fetch?

The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.


2 Answers

Headers are limited for CORS requests. See https://stackoverflow.com/a/44816592/2047472

(Use access-control-expose-headers to allow exposing headers to requests from a different origin.)

like image 30
AndyTheEntity Avatar answered Sep 19 '22 01:09

AndyTheEntity


The Headers class instance that fetch returns is an iterable, as opposed to a plain object like axios returns. Some iterable's data, such as Headers or URLSearchParams, aren't viewable from the console, you have to iterate it and console.log each element, like:

fetch('http://localhost:9876/test/sample-download', {     method: 'post',     headers: {},     body: {} }) .then(response => {   // Inspect the headers in the response   response.headers.forEach(console.log);   // OR you can do this   for(let entry of response.headers.entries()) {     console.log(entry);   } }) .catch(err => console.error(err)); 
like image 83
ccnokes Avatar answered Sep 17 '22 01:09

ccnokes