使用fetch时,文本响应为空

时间:2017-02-15 16:18:52

标签: javascript cors fetch-api

以下代码:

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)
        });

正在输出:

Request successful 0

如果我使用curl:

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

我得到一个文本形式的标记(长度!= 0)。

如果我通过以下方式输出响应头:

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

我明白了:

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

为什么我通过fetch获取文本?

1 个答案:

答案 0 :(得分:3)

删除mode: 'no-cors'

当您使用mode: 'no-cors'时,您明确指定您需要“opaque response”

您的脚本无法访问不透明响应的任何属性 - 而基本上您所能做的只是缓存它。 mode: 'no-cors'仅在使用Service Workers进行缓存时才有用。

如果你的脚本使用mode: 'no-cors'的原因是因为对服务器的跨源请求不起作用,正确的解决方案是更新服务器端代码以发送{{1}响应头和其他CORS头 - 如果您有权访问服务器,或者使用反向代理,如https://cors-anywhere.herokuapp.com/