javascript - 无法从 Express Route 查询 MySQL 数据库

标签 javascript mysql api express axios

我不知道如何从路由文件中的 Promise 查询 MySQL 数据库。我正在编写一个 RESTful API 来使用 GET 方法查询 MySQL 数据库。我使用 Express 和 Axios 来实现 Javascript promise 。 我想从 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 的常量连接?

最佳答案

我将连接到 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
        });
    });
});

关于javascript - 无法从 Express Route 查询 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980684/

相关文章:

javascript - 如何根据 onchange 每个选择框更改每个文本框的值

mysql - 返回 MIN(DATE) 和其他现有日期

api - 如何通过通过Google Apps脚本公开的API更新YouTube视频片段描述的HTML?

javascript - 如何使用 nock.js 通过 GET 请求添加参数

javascript - 如何从 TypeScript 中的 Number 类型的变量中乘以小数?

javascript - 在 Node js 上缓存数据的最佳方法

javascript - JQuery - 表单提交 - 多次?

mysql - 这个查询必须是最优的吗?如果没有,是否有改进该查询的方法

mysql - 如何为 mysql 设置 ActiveRecord 查询超时?

ruby - Soundcloud ruby​​ gem - 流派/标签过滤器不起作用