Text response is empty when using fetch

2019-01-20 14:05发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-01-20 14:37

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/.

查看更多
登录 后发表回答