简体   繁体   中英

Exporting Objects in NodeJS for API

I'm trying to write a RESTful API in NodeJS that connects to a MySQL database. I have multiple files that handle routes:

文件结构

I'm using the "mysql" package from www.npmjs.com. In app.js I create a connection object for the database but then want to use that object in both books.js and entries.js. I need to use the connection object to send queries to the database and I plan to do that in the routes files (books.js, etc.). What is the proper way to export and import that object? I'm new to NodeJS. Also, app.js is already exporting "app".

app.js:

 const express = require('express'); const app = express(); const morgan = require('morgan'); const bodyParser = require('body-parser'); const mysql = require('mysql'); const bookRoutes = require('./api/routes/books'); const entryRoutes = require('./api/routes/entries'); const connection = mysql.createConnection({ host: 'localhost', user: 'rlreader', password: process.env.MYSQL_DB_PW, database: 'books' }); app.use(morgan('dev')); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); if (req.method === 'OPTIONS') { res.header('Access-Control-Allow-Methods', 'GET'); return res.status(200).json({}); } next(); }); // Routes which should handle requests app.use('/books', bookRoutes); app.use('/entries', entryRoutes); app.use((req, res, next) => { //request, response, next const error = new Error('Not found'); error.status = 404; next(error); }); app.use((error, req, res, next) => { res.status(error.status || 500); res.json({ error: { message: error.message } }); }); module.exports = app; 

books.js:

 const express = require('express'); const router = express.Router(); const axios = require('axios'); router.get('/', (req, res, next) => { axios.get('/').then(docs => { res.status(200).json({ "hello": "hi" }) }).catch(err => { res.status(500).json({ error: err }); }) }); module.exports = router; 

GrafiCode had the answer to this one. I made a separate file called db.js

 const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'rlreader', password: process.env.MYSQL_DB_PW, database: 'books' }); module.exports = connection; 

Then, in books.js I added:

 const con = require('../../db'); 

Then I was able to use the .query() from the mysql component in multiple files.

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