如何在Express中以POST形式显示URL中的用户名?

问题描述 投票:0回答:1

我使用Express框架和mysql数据库。我想在张贴登录表单后在URL中显示数据库用户名,例如“ localhost:1001 / Home / Jay”。

我尝试使用GET方法,但在get方法中却在会话中以及URL的登录页面中获取错误,如果键入“ localhost:1001 / Home / Jay”,则其在首页中的重定向未显示我必须登录

这是路由文件夹中的user.js文件。

const express = require('express');
const mysql = require('mysql');
const bcryptjs = require('bcryptjs')
const salt = bcryptjs.genSaltSync(10);

const app = express();

var connection = mysql.createConnection({
    host:     'localhost',  // database host
    user:     'root',       // your database username
    password: 'URU143JAY',      // your database password
    port:     '1001',       // default MySQL port
    database:     'jay'
});


app.get('/login', (req, res) =>  res.render('login'));

app.post('/login', function(req, res, next){
    const name = req.body.name;
    const pass = req.body.pass;

    let errors = [];

    if(name == ''){
        errors.push({ msg: 'Please Enter Name' });
    }

    if(pass == ''){
        errors.push({ msg: 'Please Enter Password' });
    }

    req.getConnection(function(err, connection){
    connection.query("SELECT * FROM App WHERE name = '"+ name +"' ", function(err, rows, fields){
        console.log(rows[0].password);
        if(bcryptjs.compareSync(req.body.pass, rows[0].password)){
            console.log('Login');
        }else{
            errors.push({ msg: 'Wrong Password' });
        }
        if(err){
            console.log(err);
        }else{
            if(rows.length <= 0){
                    errors.push({ msg: 'Wrong Username' });
            }   
        }
        if(errors.length > 0){
            res.render('login',{
                errors,
                name,
                pass
            });
        }else{
            res.render('Home', { name: name});
        }
    });
    });
});

app.get('/Home', (req, res) => {
    res.render('Home', { name: name });
 });    

app.get('/logout', function(req, res){
    res.render('login');
});

module.exports = app;

这是登录表单login.ejs

    <form method="POST" class="register-form" id="login-form">
<div class="form-group">
<label for="your_name"><i class="zmdi zmdi-account material-icons-name"></i></label>
<input type="text" name="name" id="your_name" placeholder="Your Name" value="<%= typeof name != 'undefined' ? name : '' %>" />
</div>
<div class="form-group">
<label for="your_pass"><i class="zmdi zmdi-lock"></i></label>
<input type="password" name="pass" id="your_pass" placeholder="Password" value="<%= typeof pass != 'undefined' ? pass : '' %>" />
</div>
<div class="form-group form-button">
<input type="submit" name="signin" id="signin" class="form-submit" value="Log in" />
</div>
</form>
javascript node.js express url post
1个回答
0
投票

您必须使URL路径动态:

app.get('/Home/:id', function(req, res){
   // render your dynamic template here
   console.log(req.params.id)
});

因此渲染:“ localhost:1001 / Home / Jay”可以在更多路由示例中查看更多文档:expressJs routing

© www.soinside.com 2019 - 2024. All rights reserved.