微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在没有 res.render 的情况下将数据传递到 ejs?

如何解决如何在没有 res.render 的情况下将数据传递到 ejs?

我想在成功注册后发送一个变量值,但我必须在不使用 res.render 的情况下这样做,因为我有一些 flash 消息,如果我想显示所有这些,我必须使用 res.redirect 否则它不会工作例如:谁将尝试注册闪存消息显示“您不能使用少于 6 个字符的密码”。如何根据登录注册或注销后将变量值传递给我的 ejs 页面以隐藏或显示一些导航栏链接

// Here is my app.js file


// Config folder
require('dotenv').config();
const port = process.env.port;
const dbUrl = process.env.dbUrl;

// İmport required npms
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const connectMongo = require('connect-mongo');
const flash = require("connect-flash");
const passport = require("passport");

const app = express();

// Passport Config
require("./config/passport")(passport);

// Db Connection And Permissions
mongoose.connect(dbUrl,{
    useNewUrlParser: process.env.useNewUrlParser,useUnifiedTopology: process.env.useUnifiedTopology,useCreateIndex: process.env.useCreateIndex
});
// Express-Session Settings,Permanenet Session
const mongoStore = connectMongo(session);

app.set('trustproxy',true)
app.use(session({
    secret: 'secret',resave: true,saveUninitialized: true,store: new mongoStore({ mongooseConnection: mongoose.connection }),cookie: {
        maxAge: 86400000
    }
}));
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

// The Navbar display Links According To Log in
app.use((req,res,next) => {
    const userId = req.session;
    if (userId) {
        res.locals = {
            displayLink: true
        }
    } else {
        res.locals = {
            displayLink: false
        }
    }
    next();
});

// Set ejs settings,middleware,static folders
app.use(express.static("public"));
app.set("view engine","ejs");

// Connect flash
app.use(flash());

// Global variables
app.use((req,next) => {
    res.locals.success_msg = req.flash("success_msg");
    res.locals.error_msg = req.flash("error_msg");
    res.locals.error = req.flash("error");
    next();
});

// Import Pages
const index = require("./routes");
const user = require("./routes/user");


// Routes
app.use("/",index);
app.use("/user",user);

app.listen(port,(err) => { if (err) throw err; console.log("No problem"); });



// Here is my user.js file


const express = require("express");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcrypt")
const bodyParser = require('body-parser');
const passsport = require("passport");

router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
// Users Routing Operations
// Get Requests 
// Login Page 
router.get("/login",(req,res) => {
    res.render("pages/login");
});

// Register Page
router.get("/register",res) => {
    res.render("pages/register");
});

// Post Requests
// After Finishing Register
router.post("/register",async (req,res) => {
    const { name,email,password,rptPassword } = req.body;
    let errors = [];

    // Check required fields
    if (!name || !email || !password || !rptPassword) {
        errors.push({ msg: "Lütfen bütün alanları doldurunuz" });
    }
    // Check passwords match
    if (password !== rptPassword) {
        errors.push({ msg: "Şifreler eşleşmiyor" });
    }
    // Check password length
    if (password.length < 6) {
        errors.push({ msg: "Şifreniz en az 6 karakterden oluşmalı" });
    }
    if (errors.length > 0) {
        res.render("pages/register",{
            errors,name,rptPassword
        });
    } else {
        User.findOne({ email: req.body.email }).then(async (user) => {
            if (!user) { // If user doesnt exist before
                const salt = await bcrypt.genSalt(10);
                const hashedPassword = await bcrypt.hash(req.body.password,salt);
                req.body.password = hashedPassword;
                User.create(req.body,() => { });
                req.flash("success_msg","Kayıt Tamamlandı");
                res.redirect("/user/register");
            } else {  // If user already exist
                errors.push({ msg: "Bu Email adresi kullanımda" })
                res.render("pages/register",{
                    errors,rptPassword
                });
                res.redirect("/user/register");
            }
        });
    }
});

// Login handle
router.post("/login",next) => {
    passsport.authenticate("local",{
        successRedirect: "/",failureRedirect: "/user/login",failureFlash: true
    })(req,next);
});

// After Loging Out
router.get("/logout",res) => {
    req.logout();
    req.flash("success_msg","Çıkış Yaptınız");
    res.redirect("/user/login");
});

module.exports = router;

解决方法

我认为解决方案之一是使用多个查询字符串

然后你可以像这样处理 app.get 函数中的错误

router.post("/register",async (req,res) => {
 const { name,email,password,rptPassword } = req.body;
// Check required fields
    if (!name || !email || !password || !rptPassword) {
        res.redirect('/register?error=error-1')
    }

然后像这样处理它

// Register Page
router.get("/register",(req,res) => {
    if (req.query.error === 'error-1' )
    res.render("pages/register",{
msg: "Lütfen bütün alanları doldurunuz"
});
});

所以你可以通过给它们唯一的代码来处理所有错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。