fetch请求后的问题

fetch封装参考
http://gitbook.cn/books/59259...
引用封装好的fetch
clipboard.png

在vue中调用方法
clipboard.png

network中是返回了数据,但是当我用data接收数据并打印出来是失败的

clipboard.png

clipboard.png

是否有大佬知道问题出现在哪里??请教下!!

阅读 11.4k
6 个回答

你这样写,肯定获取不到数据了,得到的是promise对象,axios是用promise封装的,要用then才能获取到数据,
需要这样写
await filter().then((res) => { console.log(res) })

这是楼主提供的文章里fetch的封装函数,
这个是有明显问题的,当系统支持fetch 并使用的时候返回的值已经是结果了,并不是一个promise,所以
你的代码中再使用await 肯定是行不通的,但这个函数最大的问题就是,如果当检测到,系统不支持fetch ,改用XMLHttpRequest 它的返回值又是promise,
应该统一返回promise,看我在代码中注释部分

export default async(type = 'GET', url = '', data = {}, method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;
    if (type == 'GET') {
        let dataStr = ''; 
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "cors",
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        // 如果楼主想要在代码中使用await 那只要在这里返回fetch就可以了,
        //return fetch(url, requestConfig);
        //从下面一行,到else 上面部分的代码是不需要的
        try {
            var response = await fetch(url, requestConfig);
            var responseJson = await response.json();
        } catch (error) {
            throw new Error(error)
        }
        return responseJson
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}

是不是没有res.json()

看不出来有什么不对,你确定这个 response 对象是 data 打印的?

如果fetch是我以为的那样的话, 可以改写这个代码:

let data = await filter().then(res => res.json()))
console.log(data)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题