简体   繁体   中英

Redirect to another page : NodeJs

I have tried almost all the solution provided here, but as I am new to nodejs I am missing some part in my code. Please help me finding it. On clicking login button i want to redirect my page to another simple page.

Here is my login_authentication.js

window.onload = function() {


    var username    = document.getElementById("username");
    var password    = document.getElementById("password");
    var loginButton = document.getElementById("login");


    loginButton.onclick = function (req,res) {
        if ( username.value == "" || password.value == ""){
            alert("Please fill out details!");
        }else {
            //alert(username.value);
            username.value = "";
            password.value = "";

        router.get('/users', function(req, res, next) {
            // res.send('respond with a resource');
            res.render('homepage', { title: 'Thank You' });
        });
        }

    }

}

Here is app.js

app.use('/', index);
app.use('/users', users); // need to show this page rest is default code

Here is users.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
 // res.send('respond with a resource');
  res.render('homepage', { title: 'Sample' });
});

module.exports = router;

I want to redirect my page when user clicks on login button whose code is in login_authentication. Thanks for any help.

login_authentication.js使用window.location="/users"代替router.get('/users')

Assume you have some form, which has some input fields.

<form method="post" action="/thank-you" id="login">
<!-- Some input fields -->
<button type="button">Submit</button>
</form>

In your frontend js, you will handle the click event. If your validation passes, then you will submit the form to nodejs

var username    = document.getElementById("username");
var password    = document.getElementById("password");
var loginButton = document.getElementById("login");


loginButton.onclick = function (req,res) {
    if ( username.value == "" || password.value == ""){
        alert("Please fill out details!");
    }else {
        document.getElementById("login").submit();
    }

}

Here in node at this route you will receive the request, make sure it has the thank-you.html file.

//NODE
router.post('/thank-you', function(req, res) {
  res.sendFile('thank-you.html');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM