Не может выполнять запросы из другого файла (connection.query не является функцией) - PullRequest
0 голосов
/ 25 сентября 2019

я новый в node.js и базах данных.Пытаюсь сделать запрос MySQL, но я получаю эту ошибку TypeError: connection.query is not a function.

Я использую Node MySQL 2 (https://www.npmjs.com/package/mysql2) пакет;

Работает соединение и запросы в файле app.jsхорошо, но в другом файле выдает эту ошибку.

Что может быть не так с моим кодом?

app.js

const chalk = require('chalk');
const debug = require('debug')('app');
const morgan = require('morgan');
const path = require('path');
const mysql = require('mysql2');

const app = express();
const port = process.env.PORT || 3000;

const connection = mysql.createConnection({
  host: '...',
  user: '...',
  password: '...',
  database: '...',
});

connection.connect((err) => {
  if (err) {
    debug(`error connecting: ${chalk.red(err.stack)}`);
    return;
  }

  debug(`connected as id ${chalk.green(connection.threadId)}`);
});

app.use(morgan('tiny'));

app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css/')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js/')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist/')));
app.set('views', './src/views');
app.set('view engine', 'ejs');

const nav = [{ link: '/books', title: 'Books' },
  { link: '/authors', title: 'Authors' }];

const bookRouter = require('./src/routes/bookRoutes')(nav);

app.use('/books', bookRouter);
app.get('/', (req, res) => {
  res.render(
    'index',
    {
      nav,
      title: 'Library app',
    },
  );
});

app.listen(port, () => {
  debug(`listening on port ${chalk.green(port)}`);
});

module.exports = connection;

bookRoutes.js

const mysql = require('mysql2');
const debug = require('debug')('app:bookRoutes');

const connection = require('../../app');

const bookRouter = express.Router();

function router(nav) {
  const books = [
    {
      title: 'Nocturna',
      genre: 'Fantasy',
      author: 'Maya Motayne',
      read: false,
    },
    {
      title: 'Finale',
      genre: 'Fantasy',
      author: 'Stephanie Garber',
      read: false,
    },
  ];

  bookRouter.route('/')
    .get((req, res) => {
      connection.query('SELECT * FROM `books`', (error, results) => {
        debug(results);
        res.render(
          'bookListView',
          {
            nav,
            title: 'Library app',
            books,
          },
        );
      });
    });

  bookRouter.route('/:id')
    .get((req, res) => {
      const { id } = req.params;
      res.render(
        'bookView',
        {
          nav,
          title: 'Library app',
          book: books[id],
        },
      );
    });

  return bookRouter;
}

module.exports = router;

РЕДАКТИРОВАТЬ: Дерево проекта

├── app.js
├── package-lock.json
├── package.json
├── public
|  ├── css
|  |  └── styles.css
|  └── js
└── src
   ├── routes
   |  └── bookRoutes.js
   └── views
      ├── bookListView.ejs
      ├── bookView.ejs
      └── index.ejs

Спасибо за помощь.

1 Ответ

0 голосов
/ 25 сентября 2019

bookRoutes.js

const mysql = require('mysql2');
const debug = require('debug')('app:bookRoutes');

const connection = require('./../../app').connection; // identify the exported module

// the rest…
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...