Search code examples
javascriptformspostpromise

How to redirect after a POST method using Fetch?


I posted form data to an API endpoint and I want to redirect the browser to the response text. I seem to not be able to figure out what I am missing. Below is what I have been able to do so far:

  const formEl = document.querySelector("form");
  formEl.addEventListener("submit", (event) => {
    event.preventDefault();
    const formData = new FormData(formEl);
   
    
    const data = new URLSearchParams(formData);
   
    fetch("https://example.com/users", {
      method: "POST",
      body: data
    })
  
       
     .then(async response => console.log(await response.text()))
     .then(window.location.href = (response.text()))

     
  });

Solution

  • Hope this will help you.

    fetch("https://example.com/users", {
        method: "POST",
        body: data
    })
        .then(async response => response.text())
        .then(result => {
            window.location.href = result
        });