javascript - 在 NodeJS 中为 API 导出对象
问题描述
我正在尝试在连接到 MySQL 数据库的 NodeJS 中编写一个 RESTful API。我有多个处理路由的文件:
我正在使用来自 www.npmjs.com 的“mysql”包。在 app.js 中,我为数据库创建了一个连接对象,但随后想在 books.js 和 entries.js 中使用该对象。我需要使用连接对象向数据库发送查询,我计划在路由文件(books.js 等)中执行此操作。导出和导入该对象的正确方法是什么?我是 NodeJS 的新手。此外,app.js 已经在导出“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;
书籍.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() 。
推荐阅读
- algorithm - 如何计算这个细胞的概率是我的
- oracle - Oracle Schema 下每个表的行数和大小
- javascript - 如果未启用原理图,如何将节点模块添加到 Angular 项目?
- http-live-streaming - medialement.js 不适用于我在 iPhone 上的 hls
- python-3.x - 解码 Python 字符串
- python - BurpSuite 上的 POST 请求响应与 Python 不同
- java - 确定文件是否在 Java 中被 PGP 加密
- ios - 如何使单元格中的某些文本或单词不可见或可见?
- go - 如何使用 Golang 获取发布的二进制数据的文件名?
- android - 没有来自服务器的填充无法加载广告:3