gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:38:21 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com