首页 > 解决方案 > 在 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;

标签: javascriptmysqlnode.jsapi

解决方案


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() 。


推荐阅读