Postgresql 数据库不与我的简单 Node.js 服务器交互

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

与服务器和 postgresql 数据库的链接。登记册中有三个元素:全名、电子邮件和密码,但登记册中的信息似乎没有链接到数据库。也许 server.js 注册部分是问题所在。我编写了代码,以便在控制台窗口中显示错误消息,但错误消息不会出现,并且站点会继续加载而不进行处理。下面是部分代码。你能告诉我这里有什么问题吗? (我正在使用 Node.js,而且我是编码新手,刚刚开始。)

if (process.env.NODE_ENV !== "production") {
    require("dotenv").config()
}


const express = require("express")
const app = express()
const bcrypt = require("bcrypt") // Importing bcrypt package
const passport = require("passport")
const initializePassport = require("./passport-config")
const flash = require("express-flash")
const session = require("express-session")
const methodOverride = require("method-override")
const { Client } = require('pg');
const bodyParser = require('body-parser');



initializePassport(
    passport,
    email => users.find(user => user.email === email),
    id => users.find(user => user.id === id)
)

app.use(bodyParser.json());

app.use(express.urlencoded({extended: false}))
app.use(flash())
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride("_method"))

const users = [];

app.post("/login", checkNotAuthenticated, passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login",
    failureFlash: true
}))

app.post("/register", checkNotAuthenticated, async (req, res) => {

    try {
        const hashedPassword = await bcrypt.hash(req.body.password, 10);

        const newUser = {
            id: Date.now().toString(),
            name: req.body.name,
            email: req.body.email,
            password: hashedPassword
        };
        
        users.push(newUser);

const insertQuery = `INSERT INTO users (id, name, email, password) VALUES ($1, $2, $3, $4) RETURNING *`;
const values = [newUser.id, newUser.name, newUser.email, newUser.password];

client.query(insertQuery, values, (err, result) => {
    if (err) {
        console.error("Error executing query", err);
        return res.status(500).send("Server error");
    }

    console.log("User inserted:", result.rows[0]);
    res.redirect("/login");
});
} catch (e) {
    console.error(e);
    res.redirect("/register");
    }
});

// Routes
app.get('/', checkAuthenticated, (req, res) => {
    res.render("index.ejs", {name: req.user.name})
})

app.get('/login', checkNotAuthenticated, (req, res) => {
    res.render("login.ejs")
})

 app.get('/register', checkNotAuthenticated, (req, res) => {
     res.render("register.ejs")
})


// End Routes
app.delete("/logout", (req, res) => {
    req.logout(req.user, err => {
        if (err) return next(err)
            res.redirect("/")
    })
})

function checkAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return next()
    }
    res.redirect("/login")
}

function checkNotAuthenticated(req, res, next){
    if(req.isAuthenticated()){
        return res.redirect("/")

    }
    next()
}

postgresql的'用户'表

上面的代码是经过几次修改的代码,是尝试将之前在控制台操作的数据库转换为postgresql。预期的结果是注册时应该已经传输了数据库信息,但是如上所述,控制台和数据库都没有任何反应。

node.js postgresql
1个回答
0
投票

您是否使用当前参数初始化了客户端?确保仅上传发生错误的特定代码部分,而不是复制并粘贴完整代码。 尝试

const { Pool } = require('pg');

const pool = new Pool({
    user: process.env.DB_USER,
    host: process.env.DB_HOST,
    database: process.env.DB_NAME,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT || 5432
});

pool.connect((err, client, release) => {
    if (err) {
        console.error('Error connecting to the database:', err.stack);
    } else {
        console.log('Successfully connected to database');
    }
});

在注册新用户之前,请尝试检查该用户是否已经存在并首先清理输入。


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