• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

33
Views
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.

29 days ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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

29 days ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.