Text response is empty when using fetch

心不动则不痛 提交于 2020-01-21 17:27:27

问题


The following code:

fetch('http://localhost:8080/root/1487171054127/k_query_bearer_token', {
        mode: 'no-cors', credentials: 'include'
    })
        .then(function (response) {
            return response.text();
        })
        .then(function (text) {
            console.log('Request successful', text.length);
        })
        .catch(function (error) {
            log('Request failed', error)
        });

is outputting:

Request successful 0

If I use curl:

curl 'http://localhost:8080/root/1487171054127/k_query_bearer_token' \
  -H 'Cookie: JSESSIONID=CviS9IK8pcsqADdP-m0MRXX_AvUqfzjJPwk1Yytf.ee16d0a01ad5' 

I get a token in text form back (length != 0).

And if I output the response header via:

curl 'http://localhost:8080/root/1487171054127/k_query_bearer_token' 
  -H 'Cookie: JSESSIONID=CviS9IK8pcsqADdP-m0MRXX_AvUqfzjJPwk1Yytf.ee16d0a01ad5'
  --head

I get:

HTTP/1.1 200 OK
Connection: keep-alive
X-Powered-By: Undertow/1
Server: JBoss-EAP/7
Content-Type: text/plain
Content-Length: 1730
Date: Wed, 15 Feb 2017 16:17:00 GMT

Why am I getting no text via fetch?


回答1:


Remove mode: 'no-cors'.

When you use mode: 'no-cors' you’re explicitly specifying that you want an “opaque response”.

Your script can’t access any properties of an opaque response—instead essentially all you can do is cache it. mode: 'no-cors' is basically useful only when doing caching with Service Workers.

If the reason you have your script using mode: 'no-cors' is because cross-origin requests to the server otherwise won’t work, the right solution is either to update the server-side code to send the Access-Control-Allow-Origin response header and other CORS headers—if you have access to the server do to that—or else, use a reverse proxy like https://cors-anywhere.herokuapp.com/.



来源:https://stackoverflow.com/questions/42254685/text-response-is-empty-when-using-fetch

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