繁体   English   中英

在NodeJS for API中导出对象

[英]Exporting Objects in NodeJS for API

我正在尝试在连接到MySQL数据库的NodeJS中编写RESTful API。 我有多个处理路线的文件:

文件结构

我正在使用www.npmjs.com上的“ mysql”软件包。 在app.js中,我为数据库创建了一个连接对象,但随后想在books.js和entries.js中使用该对象。 我需要使用连接对象将查询发送到数据库,并且我计划在路由文件(books.js等)中执行此操作。 导出和导入该对象的正确方法是什么? 我是NodeJS的新手。 另外,app.js已经在导出“ 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对此有答案。 我制作了一个单独的文件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; 

然后,在books.js中,我添加了:

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

然后,我可以在多个文件中使用mysql组件中的.query()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM