Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请问fetch能拦截吗? #146

Closed
JackieLs opened this issue Oct 19, 2016 · 8 comments
Closed

请问fetch能拦截吗? #146

JackieLs opened this issue Oct 19, 2016 · 8 comments

Comments

@JackieLs
Copy link

if(__DEV__){
        console.log(BASE_URLS[server] + path,method)
        // http://127.0.0.1:7586/api/order/v1/orders/1
        Mock.mock('http://127.0.0.1:7586'+BASE_URLS[server]+path, method, {
            "data|1-10":[{
                "id|+1":1,
                "name|1-5":"avcx"
            }]
        })
    }
return new Promise((resolve, reject) => {
        fetch(url, {
            method: method,
            body: data,
            headers: {
                ...contentType?{
                    "Content-Type": contentType
                }:{},
                "Accept-Language": utils.locale.get()
            },
            credentials: "same-origin"
        }).then(function(resp) {
            (format === "html"?resp.text():resp.json()).then(data => {
                if (__DEV__) {
                    console.log(method, resp.url, data)
                }
                if (!resp.ok) {
                    reject({
                        type: failureType,
                        code: data.code || resp.status,
                        message: data.message || resp.statusText,
                        saveAs: saveAs,
                    })
                }

                resolve({
                    type: successType,
                    code: data.code || resp.status,
                    message: data.message || resp.statusText,
                    // Only select the wanted data
                    data: select(data, format),
                    total: data.data && data.data["total"]?data.data.total:0,
                    saveAs: saveAs
                })
            }, error => console.log(error))
        }, function(error) {
            console.log("Network Failure", error.message) //=> String
            reject({
                type: failureType,
                code: 499,
                message: error.message,
            })
        })
    })
@JackieLs
Copy link
Author

我尝试了在html里面引mock来拦截fetch但是确实拦不住,不知道是我代码的原因还是什么原因。

@peirancao
Copy link

我这也是 fetch 拦截不了 跟楼上的代码基本相同

@lintaohai1
Copy link

请求成功,但没数据返回
Mock.mock(/ab/, function (options) {
console.log(options)
return options
})
window.fetch('ab', {
method: 'get'
}).then(function (r) {
console.log(r)
}).catch(function (err) {
console.log(err)
})

@que01
Copy link

que01 commented Oct 31, 2016

@JackieLs @peirancao @lincolin 我自己的看法是不需要拦截,我目前找到两种方式可以用,一种是直接让rap返回现成data数据(因为我配合rap用的),另外一种是让它返回模板自己require('mockjs'),然后eval一下这模板 最后Mock.mock(safeeval(data));不过确实拦截不了,我建议自己写个if分支就ok了

@JackieLs
Copy link
Author

JackieLs commented Nov 2, 2016

@que01 恩,现在也是放弃了拦截fetch的想法,因为这个fetch貌似属于浏览器内部行为。跟ajax对象不太一样,虽然内部还是个ajax,但是那个内部应该是js无法接触的地方了。感谢提供方法。

@TechQuery
Copy link

Service Worker 不仅可以拦截 Fetch API,还可以做 PWA(渐进式 Web App) ——

@zjffun
Copy link

zjffun commented Jun 15, 2019

貌似作者已经不维护了,下面是一个支持拦截 fetch 的版本 zjffun/Mock-support-intercept-fetch

使用的话:

npm install @zjffun/mockjs

fetch 的拦截还是比较好实现的,因为拦截后返回 resolve 为 response 对象(通过 Response - Web APIs | MDN 创建)的 promise 对象就行。

@wll8
Copy link

wll8 commented Jan 22, 2021

可以的,把你的 mock 模版转换为 api 即可。

参考:#411 (comment)

@JackieLs JackieLs closed this as completed Feb 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants