javascript - 使用 fetch 时文本响应为空

标签 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' 

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

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

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 获取不到文本?

最佳答案

移除 mode: 'no-cors'

当你使用 no-cors 模式时,你明确指定你想要一个 “opaque response” .

您的脚本无法访问不透明响应的任何属性——实际上您所能做的就是缓存它。 no-cors 模式基本上只有在使用 Service Worker 进行缓存时才有用。

如果您的脚本使用 no-cors 模式的原因是因为对服务器的跨源请求否则将不起作用,正确的解决方案是将服务器端代码更新为发送 Access-Control-Allow-Origin 响应 header 和其他 CORS header - 如果您有权访问服务器,请执行此操作 - 否则,使用像 https://cors-anywhere.herokuapp.com/ 这样的代理.

关于javascript - 使用 fetch 时文本响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254685/

相关文章:

javascript - IE11 中的第一个 Fetch API 调用被第二个取消

JavaScript 获取 API : accessing local variable globally

javascript - 从 React 中的 CORS API 调用中得到 undefined

php - 如何检测调用是否通过 jQuery 进行

javascript - JQuery 在 Firefox 中不工作,但在 Chrome 中工作

javascript - 根据虚拟代理的随机选择产生不同结果的函数

javascript - 缺少CORS 400接头(其他问题)

tomcat - Jersey 支持 CORS 吗?

node.js - 如何实现嵌套 Node 获取调用?

javascript - 什么可能导致片段着色器中的纹理变黑?