@Vit632

Почему возникает ошибка You have tried to call .then(), .catch()?

Вопрос.
1. В чём причина проблемы?
2. Как исправить проблему?

У меня есть проект, я хочу его запустить.
Проект располагается в папке `e:\Test\Pro01\`.

Я выполнил:
- открыл консоль Windows;
- ввёл команду `cd e:\Test\Pro01\`;
- ввёл команду `node app.js`;
- результат: я получаю сообщение об ошибке;

Использую:
- Windows-10x64;
- VSCode;
- Visual Studio 2022 Community(Установлено NodeJS);
- Node.js (c:\Program Files\nodejs\node.exe);
- Wampserver64;
- MySql;

Сообщение об ошибке

e:\Test\Pro01>node app.js
Start at http://localhost:3000
You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, 
which is a programming error. 
Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' 
for a promise-compatible version of the query interface. T
o learn how to use async/await 
or Promises check out documentation 
at https://www.npmjs.com/package/mysql2#using-promise-wrapper, 
or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md
e:\Test\Pro01\node_modules\mysql2\lib\commands\query.js:41
    throw new Error(err);
    ^

Error: You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://www.npmjs.com/package/mysql2#using-promise-wrapper, or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md
    at Query.then (e:\Test\Pro01\node_modules\mysql2\lib\commands\query.js:41:11)
    at MySQLStore.query (e:\Test\Pro01\node_modules\express-mysql-session\index.js:392:12)
    at MySQLStore.<anonymous> (e:\Test\Pro01\node_modules\express-mysql-session\index.js:110:9)
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)

Node.js v18.7.0

e:\Test\Pro01>


Скриншот фрагмента кода удалён модератором.

Структура проекта. Картинки.

62e2e4d26ff15238516147.png
62e2e4dbf199a317653203.png
62e2e4e46e2c1634839539.png


Обновление-1

app.js
const express = require("express");
const bodyParser = require("body-parser");
const flash = require("connect-flash");
const expressSession = require("express-session");
const MySQLStore = require("express-mysql-session")(expressSession);
const connection = require("./db/connection");
const helpers = require("./helpers");
const config = require("./config.json");
const moment = require("moment");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const crypto = require("crypto");
const cookieParser = require("cookie-parser");

moment.locale("ru");

const app = express();

let listener = require("http").Server(app);

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  connection.query("select * from users where id = " + id, (err, rows) => {
    done(err, rows[0]);
  });
});

passport.use(
  "local-signup",
  new LocalStrategy(
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true,
    },
    (req, email, password, done) => {
      connection.query(
        "select * from users where email = ?",
        [email],
        (err, rows) => {
          if (err) {
            return done(err);
          }
          if (rows.length) {
            return done(
              null,
              false,
              req.flash("signupMessage", "That email is already taken.")
            );
          } else {
            // create the user

            crypto.pbkdf2(
              password,
              email,
              25000,
              512,
              "sha256",
              (err, hash) => {
                let newUserMysql = new Object();
                newUserMysql.email = email;
                newUserMysql.password = hash.toString("hex");

                connection.query(
                  "INSERT INTO users (email, password) values (?, ?)",
                  [newUserMysql.email, newUserMysql.password],
                  (err, rows) => {
                    newUserMysql.id = rows.insertId;
                    return done(null, newUserMysql);
                  }
                );
              }
            );
          }
        }
      );
    }
  )
);

passport.use(
  "local-login",
  new LocalStrategy(
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true,
    },
    (req, email, password, done) => {
      connection.query(
        "SELECT * FROM `users` WHERE `email` = ?",
        [email],
        (err, rows) => {
          if (err) {
            return done(err);
          }
          if (!rows.length) {
            return done(
              null,
              false,
              req.flash("loginMessage", "No user found.")
            );
          }

          crypto.pbkdf2(password, email, 25000, 512, "sha256", (err, hash) => {
            password = hash.toString("hex");
            if (!(rows[0].password == password)) {
              return done(
                null,
                false,
                req.flash("loginMessage", "Oops! Wrong password.")
              );
            }
          });

          return done(null, rows[0]);
        }
      );
    }
  )
);

const routes = require("./routes.js")(express.Router(), passport);

app
  .use(
    express.static("static", {
      maxage: "4h",
    })
  )
  .use(cookieParser())
  /*.use(i18n.init)*/
  .set("view engine", "ejs")
  .use(bodyParser.json())
  .use(
    bodyParser.urlencoded({
      extended: true,
    })
  )
  .use(
    expressSession({
      secret: config.express.secret,
      store: new MySQLStore({}, connection),
      resave: false,
      saveUninitialized: false,
    })
  )
  .use(passport.initialize())
  .use(flash())
  .use(passport.session())
  .use(async (req, res, next) => {
    res.locals.error = null;
    res.locals.helpers = helpers;
    res.locals.user = null;
    res.locals.moment = moment;
    res.locals.url = req.url;
    next();
  })
  .use(routes)
  .use((req, res, next) => {
    let err = new Error("Здесь ничего нет");
    err.status = 404;
    next(err);
  })
  .use((err, req, res, next) => {
    if (err.status != 404) {
      err.message = "Неизвестная ошибка";
    }

    return res.status(err.status || 500).render("error", {
      message: err.message,
      error: req.app.get("env") === "development" ? err : null,
      status: err.status || 500,
    });
  });

let server = listener.listen(config.express.port || 3000, () => {
  const host =
    server.address().address == "::" ? "localhost" : server.address().address;
  const port = server.address().port;
  console.log("Start at http://%s:%s", host, port);
});


Обновление-2

Картинки. Поиск: .then(), .catch(), or invoked await

62e2f7737508b486131497.png


Поиск: .then(), .catch() await

62e2f87356844418476452.png


Обновление-2
Поиск .then(), .catch() await

62e2f940cd12c120278283.png



Обновление-2
\db\connection.js
const mysql = require('mysql2');
const config = require('../config.json');
const connection = mysql.createConnection({
  host: config.mysql.host,
  user: config.mysql.user,
  password: config.mysql.password,
  database: config.mysql.db,
  charset: 'utf8_general_ci',
  multipleStatements: true
});

connection.connect();

module.exports = connection;


Картинка. Поиск "mysql2"
62e2fc79e3636394753657.png
  • Вопрос задан
  • 125 просмотров
Пригласить эксперта
Ответы на вопрос 1
Grapeoff
@Grapeoff
В чём концепция...?
Вы пытаетесь вызвать методы промиса у НЕ промиса. Там же написано: чтобы превратить всё это в промис, вам нужно вызвать метод .promise(), а вот на чём, я уже не скажу, тк вы не строчки кода не показали, зато зачем-то показали все файлы.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы