简体   繁体   中英

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. 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).

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:

/**
 * 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 .

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. You need to use a callback 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM