使用fetch polyfill模式:'no-cors'

Response status = 0 using fetch polyfill with mode: 'no-cors'

本文关键字:no-cors fetch polyfill 模式 使用      更新时间:2023-09-26

我使用'no-cors'模式获取填充,并获得响应状态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模式仅针对CDN内容,如脚本、CSS和图片,不能用于获取数据,response.status = 0是正确的行为

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

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

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

现在,不幸的是,文件和ftp url留给读者作为练习。当有疑问时,返回网络错误。

参见:https://fetch.spec.whatwg.org/#basic-fetch(文件和ftp子节)