【发布时间】:2019-09-19 23:32:21
【问题描述】:
我正在尝试在 NodeJS 中编写一个连接到 MySQL 数据库的 RESTful API。我有多个处理路由的文件:
我正在使用来自 www.npmjs.com 的“mysql”包。在 app.js 中,我为数据库创建了一个连接对象,但随后想在 book.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;
【问题讨论】:
-
在您的项目某处创建一个
db.js,您可以在其中require('mysql')并处理数据库连接。然后你可以在任何地方包含它:var sql = require('./db.js');显然路径必须反映脚本位置。本教程可能很有用codementor.io/julieisip/…
标签: javascript mysql node.js api