Вопрос.
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...romise-wrapper,
or the mysql2 documentation at https://github.com/sidorares/node-my...ise-Wrapper.md
e:\Test\Pro01\node_modules\mysql2\lib\commands\que ry.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...romise-wrapper, or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tr /mast /documenta../Promise-Wrapper.md
at Query.then (e:\Test\Pro01\node_modules\mysql2\lib\commands\qu ery.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>[/i]
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);
});
config.js
var config = {
express: {
secret: 'cfgdgN1D798646fg5dFypV3HsB4g7m9',
port: 3000,
domain: 'http://localhost:3000',
path: 'C:/server',
}
}
module.exports = config;
config.json
{
"mysql": {
"host": "localhost",
"user": "root",
"password": "",
"db": "polimedia5"
},
"express": {
"secret": "dgdf98dfg7d98tc6dSJEv4986VVF",
"port": 3000
}
}
routes.js
const multer = require('multer');
const rand = require('randomstring');
const filesStorage = multer.diskStorage({
destination: (req, file, next) => {
next(null, 'static/uploads/files');
},
filename: (req, file, next) => {
const ext = file.originalname.split('.').pop();
next(null, rand.generate({
length: 32,
charset: 'alphabetic'
}) + '.' + ext);
}
});
const filesUpload = new multer({
storage: filesStorage
});
const site = {
main: require('./controllers/main')
};
const cms = {
articles: require('./controllers/cms/articles'),
files: require('./controllers/cms/files'),
lang: require('./controllers/cms/lang'),
slideshow: require('./controllers/cms/slideshow')
};
module.exports = (app, passport) => {
app
.get('/', site.main.lang)
.get('/video', site.main.video)
.get('/slideshow', site.main.slideshow)
.get('/:lang', site.main.index)
.get('/:lang/articles', site.main.index)
.get('/:lang/articles/:id', site.main.article)
.get('/:lang/panomuseum', site.main.panomuseum)
.get('/:lang/panomuseum/2', site.main.panomuseum2)
.get('/:lang/panotheatre', site.main.panotheatre);
app
.get('/cms/lang', cms.lang.index)
.post('/cms/lang', filesUpload.any(), cms.lang.save)
.get('/cms/:lang/articles', cms.articles.index)
.post('/cms/articles/saveOrder', cms.articles.saveOrder)
.get('/cms/:lang/articles/add', cms.articles.add)
.post('/cms/:lang/articles/add', filesUpload.any(), cms.articles.postAdd)
.get('/cms/:lang/articles/:id/edit', cms.articles.edit)
.post('/cms/:lang/articles/:id/edit', filesUpload.any(), cms.articles.postEdit)
.get('/cms/:lang/articles/:id/delete', cms.articles.delete)
.get('/cms/:lang/articles/:id', cms.articles.subArticle)
.get('/cms/:lang/articles/add/:id', cms.articles.add)
.post('/cms/files/delete', cms.files.delete)
.post('/cms/files/saveFile', filesUpload.single('file'), cms.files.saveFile)
.post('/cms/files/saveThumb', filesUpload.single('thumb'), cms.files.saveThumb)
.get('/cms/slideshow', cms.slideshow.index)
.post('/cms/slideshow/save', filesUpload.any(), cms.slideshow.save);
return app;
};