简体   繁体   中英

Response.redirect() is not a function in vanilla JS?

I am trying to redirect to another page after I receive a response from the post fetch, but as the title says it doesn't work.

These are the functions:

// 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);
        });
}

Every console.log(); returns Response {type: 'basic', url: 'http://192.168.0.100/dashboard', redirected: true, status: 200, ok: true, …}

If I place response.redirect(response.status, response.url); in the first then() I get the same error.

So, does response.redirect exist in Vanilla JS ?

I don't want to use window.location.href or any other similar option because it bypasses HTTP Authentication header.

I see that you have the 'follow' argument given in the fetch.

You can check the if the response is being redirected using the code below. If it was not redirected you can simply change the window location and also force a redirect.

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

EDIT:

After doing a bit more research into the redirect method I saw that you need to switch the URL and status variables, see: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM