V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lxiian
V2EX  ›  微信

请问微信小程序的 request 怎么拦截 302 重定向啊

  •  
  •   lxiian · 2023-01-26 02:28:58 +08:00 via iPhone · 1198 次点击
    这是一个创建于 427 天前的主题,其中的信息可能已经有所发展或是发生改变。
    找了官网文档,社区官方人员说目前不支持。。。。有其他办法吗各位
    2 条回复    2023-01-26 21:07:47 +08:00
    asong
        1
    asong  
       2023-01-26 17:13:36 +08:00
    小程序怎么拦截不太清楚,但是之前是在浏览器环境中遇到过类型的问题,是通过 fetch 和 xhr 配合到一起处理的。

    不知道能不能对你有所帮助,代码逻辑如下:

    ```js
    /**
    * 获取重定向的 URL
    */
    const getRedirectURL = (url, options) => {
    return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    const { headers = {} } = options;
    // 设置请求头
    Reflect.ownKeys(headers).forEach((key) => {
    xhr.setRequestHeader(key, headers[key]);
    });
    xhr.send();
    xhr.onreadystatechange = function () {
    if (this.readyState === this.DONE) {
    // 在这里判断 responseURL 是否 和 原始 URL 一致( this.responseURL 也有可能为空)
    if (this.responseURL && this.responseURL !== url) {
    // 如果不一致,则终止请求
    resolve(this.responseURL);
    // 终止请求之后,this.responseURL 的值会被置空,所以需要在最后调用。
    this.abort();
    return;
    }
    console.log("未发生重定向,responseUR 的值为:", this.responseUR);
    resolve();
    }
    };
    xhr.onerror = function (e) {
    console.log("请求失败", e);
    resolve();
    };
    });
    };

    /**
    * 封装处理 重定向 的 Fetch
    */
    const request = (url, options) => {
    return fetch(url, options).then(async (response) => {
    // 手动处理 HTTP 重定向时,type 的值为 "opaqueredirect"
    if (response.type === "opaqueredirect") {
    const redirectURL = await getRedirectURL(url, options);
    if (!redirectURL) {
    throw new Error("未获取到重定向 URL");
    }
    // 自动对重定向的 URL 发起请求
    return request(redirectURL, options);
    }
    return response.json();
    });
    };


    (async () => {
    // 发请求
    const result = await request("/api/user/list", {
    headers: { Authorization: `Bearer xxxxxxxxx`, foo: "bar" },
    redirect: "manual",
    });
    console.log(result);
    })();
    ```

    具体思路,可以参考这里:

    https://github.com/mrlmx/blogs/issues/2
    lxiian
        2
    lxiian  
    OP
       2023-01-26 21:07:47 +08:00 via iPhone
    @asong 好的谢谢兄弟
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2339 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 16:11 · PVG 00:11 · LAX 09:11 · JFK 12:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.