Я изучаю Nodejs и пытаюсь реализовать концепцию Promise . Когда я запускаю свое приложение, я получаю следующее исключение:
Example app listening on port 3000!
TypeError: Cannot read property 'query' of undefined
at D:\nodesjapp\rsrest-api\helpers\query.js:10:8
at new Promise (<anonymous>)
at module.exports (D:\nodesjapp\rsrest-api\helpers\query.js:1:45)
at D:\nodesjapp\rsrest-api\app-middlewares\auth.js:30:22
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:5576) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
Мой помощник по запросу - query. js:
module.exports = async (conn, q, params) => new Promise(
(resolve, reject) => {
const handler = (error, result) => {
if (error) {
reject(error);
return;
}
resolve(result);
}
conn.query(q, params, handler);
}).catch(console.log);
Я вызов этого API входа в систему, который записан в auth. js:
const express = require('express');
const connection = require('../helpers/connection');
const query = require('../helpers/query');
const router = express.Router();
const dbConfig = require('../dbConfig');
const create = require('../crud/create');
router.post('/login', async (req, res) => {
const { username, password } = req.body;
const conn = await connection(dbConfig).catch(e => {});
const user = await query(
conn,
`SELECT id, username FROM USERS WHERE username=? AND password=MD5(?)`,
[username, password]
);
res.send(user[0] || { id: null, username: null });
});
module.exports = router;
Моя конфигурация базы данных записана в dbConfig. js:
const dotenv = require("dotenv")
dotenv.config();
// Get the Host from Environment or use default
const host = process.env.DB_HOST || 'localhost';
// Get the User for DB from Environment or use default
const user = process.env.DB_USER || 'root';
// Get the Password for DB from Environment or use default
const password = process.env.DB_PASS || 'root';
// Get the Database from Environment or use default
const database = process.env.DB_DATABASE || 'twitter_clone';
module.exports = { host, user, password, database };