How to redirect the user to another page after login using JavaScript Fetch API?
When using redirect mode follow in fetch() function, the client side won't be redirected to the new URL, but fetch() will follow that redirection behind the scenes and return the response from the redirect URL. To manually redirect the user after a successful login, you can follow these steps with Option 1 and 2 provided in the answer:
Option 1 - Returning RedirectResponse
- Set redirect to follow in the fetch() function (it is already set by default, but can be manually specified for clarity purposes).
- Use Response.redirected to check whether the response is the result of a request that was redirected.
- If the response is a redirect, use Response.url to get the final URL and window.location.href or window.location.replace() to redirect the user to the target URL.
Option 2 - Returning JSON response containing the redirect URL
- Have the server return a JSON response with the URL included in the JSON object.
- On client side, check if the JSON response includes the "url" key.
- If the "url" key exists, retrieve its value and redirect the user to the target URL.
The above is the detailed content of How to Manually Redirect Users After Login Using JavaScript Fetch API?. For more information, please follow other related articles on the PHP Chinese website!