gpt4 book ai didi

javascript - Node 连接闪存不适用于表单提交

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:05 26 4
gpt4 key购买 nike

我在 Node.js 中遇到连接闪存问题。我想在提交表单而不刷新页面时显示成功消息。我的应用程序如下所示:

  • 我有一个 Jquery 数据表,显示页面中的员工列表。
  • 在同一页面的数据表下方,我有一个添加新员工的表单。
    3.添加新员工后,我想使用connect-flash显示成功消息。

  • 拜托,你能告诉我我哪里做错了吗?添加新员工后未显示成功消息...

    我的代码如下:

    employeeList.js Controller 代码:
    var express = require('express');
    var session = require('express-session');
    var router = express.Router();
    var bodyParser = require('body-parser');
    const database = require('../services/database.js');
    var flash = require('connect-flash');
    router.use(session());
    router.use(flash());

    // Creates a new employee profile
    async function post(req, res, next) {
    let error = null, result = null;
    try {
    let binds = {};
    console.log("Content-Type ="+req.get('Content-Type'));
    if (req.get('Content-Type').indexOf("application/json") < 0) {
    console.log("In the Post if");
    res.set('Content-Type', 'application/json').status(415).send(JSON.stringify({
    status: 415,
    message: "Wrong content-type. Only application/json is supported",
    detailed_message: null
    }));
    return;
    } else {
    binds.FIRST_NAME = req.body.FIRST_NAME;
    binds.LAST_NAME = req.body.LAST_NAME;
    binds.EMAIL = req.body.EMAIL;
    binds.PHONE_NUMBER = req.body.PHONE_NUMBER;
    binds.HIRE_DATE = req.body.HIRE_DATE;
    binds.JOB_ID = req.body.JOB_ID;
    binds.SALARY = parseFloat(req.body.SALARY);
    binds.COMMISSION = parseFloat(req.body.COMMISSION);
    binds.MANAGER_ID = parseInt(req.body.MANAGER_ID);
    const maxEmpId = await database.simpleExecute("SELECT MAX(EMPLOYEE_ID)+1 as maxEmpId FROM employees", {}, {});
    console.log("MaxEmpId "+JSON.stringify(maxEmpId.rows[0]["MAXEMPID"]));
    binds.EMPLOYEE_ID = JSON.stringify(maxEmpId.rows[0]["MAXEMPID"]);
    console.log("Binds ="+JSON.stringify(binds));
    }
    result = await database.simpleExecute("INSERT INTO employees VALUES " +
    "(:EMPLOYEE_ID, :FIRST_NAME, :LAST_NAME, :EMAIL, :PHONE_NUMBER, " +
    ":HIRE_DATE, :JOB_ID, :SALARY, :COMMISSION, :MANAGER_ID, 60) ", binds, {});
    } catch (err) {
    error = err;
    console.log("Error ===="+err);
    next(err);
    } finally {
    if (error != null || result.rowsAffected === 0) {
    // Error
    console.log("Error ="+error);
    res.set('Content-Type', 'application/json');
    res.status(400).send(JSON.stringify({
    status: 400,
    message: (error != null && error.message.indexOf("ORA-00001") > -1) ? "Employee already exists" : "Input Error",
    detailed_message: (error != null ? error.message : "")
    }));

    } else {
    // Successfully created the resource
    console.log("Error ="+error+", Result ="+result);
    req.flash('success', 'Employee Added Successfuly');
    res.status(201).send(JSON.stringify({status: 201, message: "", detailed_message: ""}));
    }
    }
    };

    module.exports.post = post;


    **// Read all the employee_profiles (GET)**
    async function get(req, res, next) {
    try {
    console.log("In the GET of Route");
    const result = await database.simpleExecute("SELECT * FROM EMPLOYEES", [], {});
    const rows = JSON.stringify(result.rows);
    // console.log("Rows ="+rows);
    res.json(rows);
    } catch (err) {
    console.log("Error ===="+err);
    next(err);
    }
    };

    module.exports.get = get;

    employeeRouter.js 代码:
    var express = require('express');
    var session = require('express-session');
    var router = express.Router();
    var bodyParser = require('body-parser');
    const employeesList = require('../controllers/employeesList');
    const employee = require('../controllers/showEmployee');
    var flash = require('connect-flash');
    router.use(session());
    router.use(flash());

    router.route('/employees').get(function(req, res, next) {
    try {
    res.render("index", { messages: req.flash('success') });
    console.log('FLASH MESSAGES-->',req.flash());
    } catch (err) {
    console.log("Error ===="+err);
    next(err);
    }
    });

    app.js 代码:
    var createError = require('http-errors');
    var express = require('express');
    var session = require('express-session');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    var flash = require('connect-flash');

    // Database
    var indexRouter = require('./routes/index');
    var employeesRouter = require('./routes/employeesRouter');
    var app = express();
    app.use(flash());

    // view engine setup
    app.set('view engine', 'pug');
    app.set('views', path.join(__dirname, 'views'));
    app.use(express.static(path.join(__dirname, '/')));
    app.use(express.static(path.join(__dirname, 'public')));

    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());

    //Setup Session MiddleWare with secret and session options
    var sessionMiddleware = session({
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true
    });

    app.use(sessionMiddleware);
    app.use(function (req, res, next) {
    //req.session.test = "test";
    req.flash('info', req.flash());
    next();
    });

    app.use('/', employeesRouter);
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
    next(createError(404));
    });

    // error handler
    app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
    });

    module.exports = app;

    索引哈巴狗文件:

    我保持条件显示这样的消息
    //Message
    #testing
    if (messages.length>0)
    div.alert.alert-danger #{ messages }

    最佳答案

    根据 Chris G 的建议,我已经向 JSON 添加了一条响应消息,该消息被发送回并在我的 pug 模板中使用 Jquery 呈现它。

    关于javascript - Node 连接闪存不适用于表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56075632/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com