skip to Main Content

Good people!
Why doesn’t it redirect when I click the "Submit" button on the login page?

code in index.js file:

app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.join(__dirname, 'public'), { "extensions": ["html", "css", "js"] }));

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/login.html'));
});

app.post('/login', (req, res) => {
    console.log(req.body.username);
    res.redirect('/chat');
});

app.get('/chat', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/chat.html'));
});

and login.html:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/login.css">
    <title>Log in</title>
</head>

<body>
    
    <div class="wrapper">
        <form action="/login" method="post" class="form">
            <h1>Enter to the chat</h1>
            <div class="username-container">
                <label for="username">Your name:</label>
                <input type="text" name="username" id="username" maxlength="10" required>
            </div>
            <button type="submit" id="submit">Submit</button>
        </form>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript" src="./js/login.js"></script>
</body>

project structure:

  ./public
    ./css
      ./login.css
      ./styles.css
    ./js
      ./login.js
      ./main.js
    ./chat.html
    ./login.html
  ./index.js

To the browser console using the code from login.js:

form.addEventListener('submit', event => {
       event.preventDefault();

       console.log('Form submitted');

       socket.emit('login', {
           username: username.value.trim()
       });
});

"Form submitted" is displayed

But when I was still figuring out how to connect styles to the server in principle, when they were not connected, everything was fine with the redirect. By the way, there were MIME TYPE errors.

There are currently no errors in the console.

2

Answers


  1. The node server is receiving a POST request but needs to redirect it to a different server as GET request. So you can try using

    app.post('/login', (req, res) => {
        res.redirect(308, '/chat');
    });
    

    According to the documentation, 308 preserves not only the HTTP method, but also indicates this is a permanent redirect.

    Login or Signup to reply.
  2. Try this in your index.js and let’s see it’ll help or not.

    app.use(express.static(path.join(__dirname, 'public'), { "extensions": ["html", "css", "js"] }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search