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));
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 .
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.
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.)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With