【问题标题】:Can't Query MySQL Database from Express Route无法从 Express Route 查询 MySQL 数据库
【发布时间】:2019-09-17 19:14:33
【问题描述】:

我不知道如何从我的路由文件中的 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 连接?

【问题讨论】:

  • 那么问题出在哪里?
  • 我知道要使用什么 SQL 代码,但我不知道如何提出请求。
  • 你看过sequelize吗?

标签: javascript mysql api express axios


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    • 2019-09-26
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多