How to get Header Location value from a Fetch request in browser

浪子不回头ぞ 提交于 2020-05-11 05:35:18

问题


From a ReactJS - Redux front app, I try to get the Location Header value of an REST API response.

When I Curl this :

curl -i -X POST -H "Authorization: Bearer MYTOKEN" https://url.company.com/api/v1.0/tasks/

I Have this answer :

HTTP/1.1 202 ACCEPTED
Server: nginx
Date: Fri, 12 Aug 2016 15:55:47 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Location: https://url.company.com/api/v1.0/tasks/status/idstatus

When I make a Fetch in ReactJS

    var url = 'https://url.company.com/api/v1.0/tasks/'
    fetch(url, {
            method: 'post',
            credentials: 'omit',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            }
     )

I don't have any Headers in the response object : No header in Fetch request

I tried all the response.headers functions I've found in https://developer.mozilla.org/en-US/docs/Web/API/Headers :

response.headers.get('Location');

But well, as headers is empty, I have empty results.

Do you know why I can't get a proper Header object filled with the headers values ?


回答1:


Thanks to John, I've found the answer.

I just had to put

Access-Control-Expose-Headers: Location

To my response headers and it worked, so now I can access Location value with :

response.headers.get('Location');

Thx John !




回答2:


Besides to expose the Location Header in the server.

I just could access the location in the react application with:

response.headers.location;


来源:https://stackoverflow.com/questions/38927335/how-to-get-header-location-value-from-a-fetch-request-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!