【问题标题】:Response status = 0 using fetch polyfill with mode: 'no-cors'响应状态 = 0 使用 fetch polyfill 模式:'no-cors'
【发布时间】:2015-12-26 13:49:39
【问题描述】:

我正在使用带有“no-cors”模式的fetch polyfill 并获得响应状态 0。在开发人员工具中,我可以看到响应包含请求的数据。

客户端代码:

const BASE_CONFIG = {
    credentials: 'include',
    mode: 'no-cors'
};

let checkStatus = (response) => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    } else {
        var error = new Error(response.statusText);
        error.response = response;
        throw error;
    }
};

function GET(url, urlParams={}, config={}) {
    let requestConfig = {
        method: 'get'
    };
  
    Object.assign(requestConfig, BASE_CONFIG, config);
    return fetch(url, requestConfig)
            .then(checkStatus)
            .then(parseJSON);
}

GET('http://other.domain,{})

Beckend nodejs (Express.js) 简化响应处理程序:

function getData(req, res) {
    var responseData = {data: 'test'};
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.writeHead(200, {"Content-Type": "application/json"});
    return res.end(JSON.stringify(responseData));
}

知道我做错了什么吗? 谢谢!

【问题讨论】:

  • 如果要阅读响应正文,不能使用no-cors

标签: javascript http get fetch-api


【解决方案1】:

no-cors模式只针对CDN内容,如脚本、CSS、图片,不能用于获取数据,response.status = 0是正确的行为

【讨论】:

    【解决方案2】:

    我不知道你是否使用 file: 协议,但在这种情况下你可以得到响应状态 0。

    Chrome 和 Firefox 的原生实现都不支持获取本地文件

    见:https://github.com/github/fetch/pull/92#issuecomment-140665932

    目前,不幸的是,文件和 ftp URL 留给读者作为练习。如有疑问,请返回网络错误。

    请参阅:https://fetch.spec.whatwg.org/#basic-fetch(文件和 ftp 子部分)

    【讨论】:

    • 任何时候你使用“no-cors”,它都会发回一个“不透明”的响应,你就无法访问 json。在这种情况下,不确定“no-cors”有什么用?有人吗?
    猜你喜欢
    • 2017-09-01
    • 2021-03-20
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多