无法从Express Route查询MySQL数据库

时间:2019-09-17 19:14:33

标签: javascript mysql api express axios

我不知道如何从路由文件中的Promise查询MySQL数据库。我正在编写一个RESTful API,以使用GET方法查询MySQL数据库。我将Express和Axios用于Javascript承诺。 我想从SQL表中获取书籍列表以及返回的JSON中有多少个列表的计数。

server.js

const http = require('http');
const app = require('./app');

const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);

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');
//do I import something for mysql here?

router.get('/', (req, res, next) => {
    axios.get('/').then(docs => {
        res.status(200).json({
            "hello": "hi" //want to query MySQL database here
        })
    }).catch(err => {
        res.status(500).json({
            error: err
        });
    })
});

module.exports = router;

任何帮助将不胜感激。对于初学者,如何获得从app.js到books.js的const连接?

1 个答案:

答案 0 :(得分:0)

我将连接到MySQL数据库的代码移到了一个单独的文件中,并包含以下内容:

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

接下来,我必须正确返回响应:

router.get('/', (req, res, next) => {
    let responseData = axios.get('/').then(docs => {
        const sql = "SELECT title, id FROM books";
        con.query(sql, function (err, result) {
            if (err) {
                console.log("error happened");
            }
            return res.status(200).json(result);
        });
    }).catch(err => {
        res.status(500).json({
            error: err
        });
    });
});