简体   繁体   中英

database connection in node.js, multiple script files

How can I connect these two files an error connection not defined is occurring ReferenceError: connection is not defined

I am using MySQL database I have cut many of my code the only problem is in connecting these two files

// router file
const express = require('express');
const router = express.Router();


  // form for note creation
  router.get('/create', (req, res) => {
    res.render('notes/create')
  })
  
  // creating note
  router.post('/', (req, res) => {
    let note = {heading:req.body.heading, body:req.body.body};
    const sql = 'INSERT INTO note SET ?';
    connection.query(sql,note, (err, rows) => {
      if (err)
      res.send(err);
      else
      res.redirect(`/notes`)
    });
  })
  module.exports = router;
// main app file

const express = require('express');
const app = express();
const mysql = require('mysql');
const note = require('./routes/note');


const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'pass1',
  database: 'notetakingapp',
  multipleStatements: true
})

connection.connect((err) => {
  if (err) throw err;
  console.log('Database Connected')
})
app.use('/notes', note)

app.listen(3000, () => {
  console.log('on port 3000')
})

You didn't pass the connection variable so it's normal that it's not defined in other files. You can add code in app file like this

app.set('connection', connection)

and then in the other files

const connection = req.app.get('connection')

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