简体   繁体   English

以前工作的 Node.JS 项目不再工作 - 错误:Route.post() 需要回调 function 但得到了 [object Undefined]

[英]Previously working Node.JS project no longer working - Error: Route.post() requires a callback function but got a [object Undefined]

I usually try to ask questions with way more detail and much more specific wording to my question titles, but I'm at a loss as to what the problem is that I have and where to look for the answer.我通常会尝试以更详细的方式和更具体的措辞来提问我的问题标题,但我不知道我遇到了什么问题以及在哪里寻找答案。

I just learned how to use Node JS over the past few months and left created this project, left it be for a month, and have just come back to try to open it again after not using Node JS since.在过去的几个月里,我刚刚学习了如何使用 Node JS,然后创建了这个项目,将其放置了一个月,并且在没有使用 Node JS 之后才回来尝试再次打开它。 Part of the reason why I'm stumped is that there were no errors the last time I ran the project, so I'm not sure if it's something that I messed up or maybe something external that has changed since then.我感到困惑的部分原因是我上次运行该项目时没有出现任何错误,所以我不确定这是我搞砸了还是从那时起发生了一些外部变化。 I tried to even run the project on a different computer and received the same error.我什至试图在另一台计算机上运行该项目并收到相同的错误。

I've googled the error that's coming up when I try to 'node server.js' to start the project up and the previous questions/answers don't seem to be relevant, or as far I can tell (I could definitely just be missing something though).我用谷歌搜索了当我尝试“node server.js”启动项目时出现的错误,之前的问题/答案似乎不相关,或者据我所知(我绝对可以虽然缺少一些东西)。

Any pointers in a direction of what to look for in my code or requests for additional information to post here are welcome.欢迎任何关于在我的代码中查找什么的指示或请求在此处发布的其他信息。

Here is the Error:这是错误:

Error: Route.post() requires a callback function but got a [object Undefined]
at Route.<computed> [as post] (C:\xampp\htdocs\web_programming\node_final_project\node_project\node_modules\express\lib\router\route.js:202:15)
at Function.app.<computed> [as post] (C:\xampp\htdocs\web_programming\node_final_project\node_project\node_modules\express\lib\application.js:482:19)
at Object.<anonymous> (C:\xampp\htdocs\web_programming\node_final_project\node_project\server.js:125:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47

Here is code from server.js:这是来自 server.js 的代码:

/**
 * Required External Modules
 */
const express = require('express');
const path = require("path");
var mysql = require('mysql');
var url = require('url');
var nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const request = require('request');
const { check, validationResult } = require('express-validator');
//const { Pool } = require('pg');
//const pool = new Pool({
//  connectionString: process.env.DATABASE_URL,
//  ssl: {
//    rejectUnauthorized: false
//  }
//});

/**
 * App Variables
 */
const app = express();
const port = process.env.PORT || "8000"
const GOOGLE_RECAPTCHA_KEY = "...";
const GOOGLE_RECAPTCHA_SECRET = "...";
var contactValidate = [
    check('fname').trim().escape(),
    check('lname').trim().escape(),
    check('email', 'Must Be an Email Address').trim().escape().normalizeEmail(),
    check('message').trim().escape()];

/**
 *  App Configuration
 */
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

/**
 * Routes Definitions
 */
app.get(["/", "/home"], (req, res) => {
    res.render("index", {
        title: "Home"
    });
});

app.get("/skippy", (req, res) => {
    res.render("skippy", {
        title: "Skippy",
        profile: {
            name: "Skippy",
            age: 11,
            breed: "...",
            allergies: "...",
            foods: "...h",
            toys: "...",
            activities: "..."
        }
    });

});

app.get("/sandy", (req, res) => {
    res.render("sandy", {
        title: "Sandy",
        profile: {
            name: "...",
            age: 10,
            breed: "...",
            allergies: "...",
            foods: "...",
            toys: "....",
            activities: "..."
        }
    });
});

app.get("/message", (req, res) => {
    console.log("Getting messages...");
    getMessages(req, res);
});

app.post("/posted", (req, res) => {
    postMessage(req, res);
});

app.get("/contact", (req, res) => {
    res.render("contact", {
        title: "Contact",
        key: GOOGLE_RECAPTCHA_KEY
    });
});

app.post("/submit", (req, res) => {
    if (
        req.body.captcha === undefined ||
        req.body.captcha === '' ||
        req.body.captcha === null
    ) {
        return res.json({
            "success": false,
            "msg": "Please select captcha"
        });
    }

    //Verify URL
    const verifyUrl = `https://google.com/recaptcha/api/siteverify?secret=${GOOGLE_RECAPTCHA_SECRET}&response=${req.body.captcha}&remote.ip=${req.connection.remoteAddress}`;

    //Make Request to Verify URL
    request(verifyUrl, (err, response, body) => {
        body = JSON.parse(body);
        //If not successful
        if (body.success != undefined && !body.success) {
            return res.json({
                "success": false,
                "msg": "Failed captcha verification"
            });
        }

        //If successful
        return res.json({
            "success": true,
            "msg": "Captcha passed"
        });
    });

});

app.post("/submitted", contactValidate,(req, res) => {
    emailContact(req, res);
});

app.get("/submitted", (req, res) => {
    res.render("submitted", {
        title: "Submitted Contact Form"
    });
});

/**
 * Server Activation
 */
app.listen(port, () => {
    console.log(`Listening to requests on http://localhost:${port}`);
});

/**
 * App Functions
 */
function getMySQLConnection() {
    return mysql.createConnection({
        host: "...",
        user: "...",
        password: "",
        database: "..."
    });
}

function postMessage(req, res) {
    // Connect to MySQL database.
    var conn = getMySQLConnection();
    conn.connect(function (err) {
        if (err) {
            res.status(500).json({
                "status_code": 500,
                "status_message": "internal server error"
            });
            throw err;
        } else {
            console.log(new Date().toUTCString() + "Connected to skippy_and_sandy DB");
        }
        console.log("You submitted a message form.");
        console.log('Got body:', req.body);
        // Do the query to insert data.
        var sql = "INSERT INTO messages (name, location,message) VALUES ('" + req.body.name + "', '" + req.body.location + "', '" + req.body.message + "')";
        console.log("sql query: " + sql);
        conn.query(sql, function (err, rows, fields) {
            if (err) throw error
            else {
                console.log("inserted into the messages table");
            }
            res.redirect("/message");
        });

    });
}

function getMessages(req, res) {
    var messagesList = [];

    // Connect to MySQL database.
    var conn = getMySQLConnection();

    // Get Messages
    conn.connect(function (err) {
        if (err) {
            res.status(500).json({
                "status_code": 500,
                "status_message": "internal server error"
            });
            throw err;
        } else {
            console.log(new Date().toUTCString() + " Connected to skippy_and_sandy DB");
        }

        conn.query("SELECT * FROM messages", function (err, result, fields) {
            if (err) {
                console.log("error here");
                console.log("err");
                throw err;
            }
            console.log(result);
            result.forEach(message => {
                var Message = {
                    'date': message.date.toLocaleString("en-US"),
                    'name': message.name,
                    'location': message.location,
                    'message': message.message
                }
                messagesList.push(Message);
            });
            //log all messages from table
            for (var i = 0; i < messagesList.length; i++) {
                console.log(messagesList[i]);
            }
            console.log("done looping from method");
            res.render("message", {
                title: "Public Message Board",
                list: messagesList
            });
            console.log(messagesList.length);
        });
    });
}

function emailContact(req, res) {
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '...',
            pass: '...'
        }
    });

    var mailOptions = {
        from: '...',
        to: '...',
        replyTo: req.body.email,
        subject: 'Form Submission from: ' + req.body.fname + ' ' + req.body.lname,
        html: '<h2>Form Submission Details</h2><br><h3>First Name: ' + req.body.fname + '</h3><h3>Last Name: ' + req.body.lname + '</h3><h3>Email: ' + req.body.email + '</h3><h3>Message: ' + req.body.message + '</h3>'
    };

    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            console.log('Email sent: ' + info.response);
            res.redirect("/submitted");
        }
    });
}

Please let me know if there's anything that I should add that would be relevant/helpful.请让我知道是否有任何我应该添加的相关/有用的内容。

Main problem in the code is how you use contactValidate .代码中的主要问题是您如何使用contactValidate

As it described in the error Route.post() requires a callback function but got a [object Undefined] you can't use an array for post.正如错误Route.post() requires a callback function but got a [object Undefined]你不能使用数组进行发布。 You need to use a callback function.您需要使用回调 function。

Instead of using check function in the array one by one, I reccomend you to use checkSchemahttps://express-validator.github.io/docs/schema-validation.html我建议您使用checkSchemahttps://express-validator.github.io/docs/schema-validation.html,而不是在数组中一个一个地使用 check function

app.post("/submitted", checkSchema(/* add your validations here as an object */),(req, res) => {
    emailContact(req, res);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js-错误:Route.post()需要回调函数,但得到了[对象未定义] - Node.js - Error: Route.post() requires a callback function but got a [object Undefined] Node.js Express.js MongoDB:route.post()需要回调函数,但有一个[object Undefined] - Node.js Express.js MongoDB: route.post() requires callback functions but got a [object Undefined] Express.js 应用程序错误导致 Route.post() 需要回调 function 但得到 [object Undefined] 错误 - Express.js application bug causes Route.post() requires a callback function but got a [object Undefined] error Route.post() 需要一个回调函数,但在 ExpressJs 中得到了一个 [object Undefined] - Route.post() requires a callback function but got a [object Undefined] In ExpressJs Route.post() 需要一个回调函数,但得到了一个 [object Undefined] - Route.post() requires a callback function but got a [object Undefined] 错误:Route.post() 需要一个回调函数,但得到了一个 [object Object] - Error: Route.post() requires a callback function but got a [object Object] 如何解决此路由错误:“Route.post() 需要回调函数,但得到了 [object Undefined]” - how to solve this route error: "Route.post() requires a callback function but got a [object Undefined]" Firebase - ⚠ 错误:Route.post() 需要回调 function 但得到 [object Undefined] - Firebase - ⚠ Error: Route.post() requires a callback function but got a [object Undefined] Route.post() 需要回调 function 但得到了一个 [object Undefined]? 为什么会出现此错误? - Route.post() requires a callback function but got a [object Undefined]? Why am I getting this error? 我的Node.js获得了Route.post()获得了对象未定义错误 - My Node.js gets an Route.post() got a object Undefined error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM