我正在用node.js和mysql构建一个rest api。但在我的GET中,我收到了一个使用mysql的router.get“无法得到任何响应”的错误。 这是我的代码,它有帮助。
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 userRoutes = require('./api/routes/user');
var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
res.locals.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
res.locals.connection.connect();
next();
});
user.js的
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;
在那个user.js中,如果我在不使用mysql的情况下使用get,则连接可以正常工作。
答案 0 :(得分:0)
您需要了解JavaScript性质(异步编程),并且您不能在每个请求中打开mysql
连接,您可以使用连接池并保持连接打开,只需获取连接并在查询后释放它。
已更新app.js
const express = require('express');
const app = express();
const userRoutes = require('./api/routes/user');
const mysql = require('mysql');
//Database connection
const pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : ' ',
database : 'achai_db'
});
app.use(function(req, res, next){
pool.getConnection(function(err, connection) {
res.locals.connection = connection;
next(err);
});
});
已更新user.js
const express = require('express');
const router = express.Router();
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from users', function (error, results, fields) {
res.locals.connection.release();
if (error) throw error;
//res.json({"status": 200, "error": null, "response": results});
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});
module.exports = router;