"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Redirect User to Another Page After Login Using JavaScript Fetch API?

How to Redirect User to Another Page After Login Using JavaScript Fetch API?

Published on 2024-11-08
Browse:604

How to Redirect User to Another Page After Login Using JavaScript Fetch API?

How to Redirect the User to Another Page After Login Using JavaScript Fetch API?

In the code provided, the JavaScript fetch() method is used to send a POST request to a backend endpoint with a token obtained from Google. Upon validation of the token in the backend, a RedirectResponse is returned with a status code of 303. However, the redirect does not occur in the browser.

Option 1: Returning RedirectResponse

The fetch() function follows redirect responses by default. Therefore, you can use the Response.redirected and Response.url properties in the fetch() response to manually redirect the user.

Working Example:

fetch('http://localhost:8000/login', {
  method: 'POST',
  headers: { ... },
  body: { ... },
  redirect: 'follow'
})
.then(res => {
  if (res.redirected) {
    window.location.href = res.url;
  } else {
    // Handle non-redirect responses
  }
})

Option 2: Returning JSON Response with Redirect URL

Alternatively, the backend can return a JSON response containing the redirect URL. On the frontend, you can check for the "url" key in the response and redirect the user accordingly.

Working Example:

fetch('http://localhost:8000/login', {
  method: 'POST',
  headers: { ... },
  body: { ... },
})
.then(res => res.json())
.then(data => {
  if (data.url) {
    window.location.href = data.url;
  } else {
    // Handle non-redirect responses
  }
})

Option 3: Using HTML

If using fetch() is not required, you can use a traditional HTML form with a submit button. When the form is submitted, the browser will automatically handle the redirect if a RedirectResponse is returned from the server.

Release Statement This article is reprinted at: 1729207576 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3