Home >Backend Development >Python Tutorial >How to Redirect Users After Login Using the JavaScript Fetch API?
When using the fetch() API to make a POST request to a server for login, redirecting the user to another page can be achieved using one of the following options:
By default, the fetch() function in JavaScript automatically follows redirects. So, when the server returns a RedirectResponse, the fetch() request will follow the redirection and return the response from the redirect URL.
To determine if the response is the result of a redirection, check if Response.redirected is True. If so, Response.url will contain the final URL after any redirects. Use window.location.href or window.location.replace() to redirect the user to the target URL.
Instead of returning a RedirectResponse, the server can return a JSON response containing the target URL as a key-value pair (e.g., { "url": "/welcome" }). On the client side, check if the JSON response includes the url key, and if so, use window.location.href or window.location.replace() to redirect the user.
If using fetch() is not required, consider using a traditional HTML form for login. When the user submits the form, a POST request will be sent to the server. The server can then return a RedirectResponse, and the browser will automatically redirect the user to the target URL.
The above is the detailed content of How to Redirect Users After Login Using the JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!