How do I redirect a user after login with fetch()

Gabriel Lobo

I'm making a node.js app with express and I'm trying to make a login form for my users, I want to have a Javascript file with a fetch() call to make a POST request to my API to login the user, but I can't seem to redirect the user after a successful login, it stays on the same page, I can log the result from fetch but can't redirect.

Here's the server code (authentication is working fine, just the redirect isn't):

router.post('/users/login', login.none() , async (req, res) => {
    try {
        const user = await User.findByCredentials(req.body.email, req.body.password)
        const token = await user.generateAuthToken()
        res.cookie('access_token', 'Bearer ' + token, {
            expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours
            })
            .redirect('/users/me')
        
    } catch (error) {
        res.status(404).send()
    }
})

Here is my HTML + JS code (I know I don't need to have a function for this and can just use action="/users/login", but I want to use javascript to handle errors with the login):

<h1>Welcome</h1>
<form id="loginform" action="/users/login" method="POST">
    <input type="text" name="email" id="email" placeholder="email">
    <input type="password" name="password" id="password" placeholder="password">
    <input type="submit">
</form>
<script>
    const loginForm = document.querySelector('#loginform');
    loginForm.addEventListener('submit', (e)=> {
        e.preventDefault()
        fetch('/users/login', { method: 'POST', body: new FormData(loginForm)} )
    })
</script>
Code-Apprentice

Here is my HTML + JS code (I know I don't need to have a function for this and can just use action="/users/login", but I want to use javascript to handle errors with the login):

TL;DR Use action instead of fetch(). If you need help with the error handling part, post a new question about it.

Using action for form submission and JavaScript for error handling are not mutually exclusive. The problem here is that fetch() makes an AJAX request which returns the response as a value directly in the current page. It will not automatically redirect according to the response code. You can add some additional logic to do this, but why make this more complicated than necessary.

Instead add an action attribute to your <form>:

<form name="login" id="loginform" action="/users/login/" method="POST">

Then write JavaScript to do your error handling. Only call preventDefault() when there is an error to prevent the form submission. But allow normal submission when there is no errors.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to I redirect after login while using jwt authentication

分類Dev

Facebook login - no redirect after login

分類Dev

ring redirect after login

分類Dev

Redirect to a servlet after login?

分類Dev

How to redirect user after submitting form with React

分類Dev

How do I store total points after user input in Javascript?

分類Dev

In Django, after a login how can I detect which auth backend authenticated the user?

分類Dev

Laravel 5.5 - How can I add a custom value to Auth::user() after successfully login

分類Dev

How do I login as root?

分類Dev

How to login user to a google webpage after successful OAuth 2.0 login?

分類Dev

Laravel :How make correct redirect to after login in multiauth

分類Dev

How do fetch remote branch after I cloned repo with git clone --depth 1

分類Dev

How do I use row_number in Hive query to get the latest user login?

分類Dev

How Do I set a cookie in fetch request?

分類Dev

redirect to next/route action, not the last after user login/registration symfony security

分類Dev

I keep getting RelatedObjectDoesNotExist at /admin/login/. How do I successfully create user profiles in Django via a one to one relationship?

分類Dev

How to prevent user to go to login page after logged in in Vuejs?

分類Dev

how to call a plugin after user login in joomla 3.0

分類Dev

How do I force to open a specific activity after a user set the alarm?

分類Dev

ActiveAdmin redirect after login doesn't work

分類Dev

After Login Execute A Function And Redirect To Previous Page

分類Dev

How do i send form data to php using fetch in nativescript?

分類Dev

How can I add JWT automatically after login?

分類Dev

How do I redirect assembly binding to the current version or higher?

分類Dev

How do I redirect to another page on form submit?

分類Dev

How do I reward the user daily?

分類Dev

How do I make a rectangle with user input?

分類Dev

In ASP.NET Core 2.1 how do I add menu items after the user has logged in based on Role?

分類Dev

How to redirect the user to another page after they have logged in with Ion Auth CodeIgniter

Related 関連記事

  1. 1

    How to I redirect after login while using jwt authentication

  2. 2

    Facebook login - no redirect after login

  3. 3

    ring redirect after login

  4. 4

    Redirect to a servlet after login?

  5. 5

    How to redirect user after submitting form with React

  6. 6

    How do I store total points after user input in Javascript?

  7. 7

    In Django, after a login how can I detect which auth backend authenticated the user?

  8. 8

    Laravel 5.5 - How can I add a custom value to Auth::user() after successfully login

  9. 9

    How do I login as root?

  10. 10

    How to login user to a google webpage after successful OAuth 2.0 login?

  11. 11

    Laravel :How make correct redirect to after login in multiauth

  12. 12

    How do fetch remote branch after I cloned repo with git clone --depth 1

  13. 13

    How do I use row_number in Hive query to get the latest user login?

  14. 14

    How Do I set a cookie in fetch request?

  15. 15

    redirect to next/route action, not the last after user login/registration symfony security

  16. 16

    I keep getting RelatedObjectDoesNotExist at /admin/login/. How do I successfully create user profiles in Django via a one to one relationship?

  17. 17

    How to prevent user to go to login page after logged in in Vuejs?

  18. 18

    how to call a plugin after user login in joomla 3.0

  19. 19

    How do I force to open a specific activity after a user set the alarm?

  20. 20

    ActiveAdmin redirect after login doesn't work

  21. 21

    After Login Execute A Function And Redirect To Previous Page

  22. 22

    How do i send form data to php using fetch in nativescript?

  23. 23

    How can I add JWT automatically after login?

  24. 24

    How do I redirect assembly binding to the current version or higher?

  25. 25

    How do I redirect to another page on form submit?

  26. 26

    How do I reward the user daily?

  27. 27

    How do I make a rectangle with user input?

  28. 28

    In ASP.NET Core 2.1 how do I add menu items after the user has logged in based on Role?

  29. 29

    How to redirect the user to another page after they have logged in with Ion Auth CodeIgniter

ホットタグ

アーカイブ