首页 > 解决方案 > Response.redirect() 不是 vanilla JS 中的函数?

问题描述

在收到来自 post fetch 的响应后,我试图重定向到另一个页面,但正如标题所说,它不起作用。

这些是功能:

// send/post json
async function postData(json_data, api_path) {
    const response = await fetch(api_path, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
        body: json_data,
        redirect: 'follow'
    });
    console.log("postData response: ", response);
    return response;
}

// send JSON data to server on /api/${destination}
function saveSettings(form, destination) {
    let json_data = toJSONstring(form);
    let res;
    console.log(json_data);
    postData(json_data, `/api/${destination}`)
        .then((response) => {
            res = response;
            if (!response.ok) {
                throw new Error(`HTTP error, status = ${response.status}`);
            }
            return response.text();
        }).then(text => {
            if (destination === 'network/post') {
                connected = false;
                updatingToast(`You are no longer connected to the device !`, false);
                updatingToast(`Please navigate to ${text}`, true, text);
            }
            console.log('res: ', res);
            res.redirect(res.status, res.url);
        });
}

每一次console.log();回报Response {type: 'basic', url: 'http://192.168.0.100/dashboard', redirected: true, status: 200, ok: true, …}

如果我放在第一位response.redirect(response.status, response.url);then()我会得到同样的错误。

那么,Vanilla JS 中是否存在response.redirect ?

我不想使用window.location.href或任何其他类似选项,因为它绕过了 HTTP 身份验证标头。

标签: javascript

解决方案


我看到你在 fetch 中给出了 'follow' 参数。

您可以使用下面的代码检查响应是否被重定向。如果它没有被重定向,您可以简单地更改窗口位置并强制重定向。

if (res.redirected) {
    window.location.href = res.url;
}

编辑:

在对重定向方法进行了更多研究之后,我发现您需要切换 URL 和状态变量,请参阅:https ://developer.mozilla.org/en-US/docs/Web/API/Response/redirect


推荐阅读