NodeJS是否可以在单个路由页面中运行多个sql查询?

时间:2020-04-21 21:28:20

标签: mysql node.js database express

我正在尝试使用NodeJS从mysql数据库中提取数据。我需要运行多个路由,但是是否可以在一个route.js页面中运行这些路由?我会在下面附加我的代码,但是当我将路由输入到浏览器即localhost:3000 / a时,它不起作用,并且我希望能够拥有多个主机名,例如localhost:3000 / b以及c和d吗?

我尝试了不同的路线和路径,但不能让它们起作用,对此我们深表感谢

app.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mysql= require('mysql');
var http = require('http');


var index = require('./routes/index');
var users = require('./routes/users');
var candidates = require('./routes/users')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));


//Database connection
app.use(function(req, res, next){
    global.connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        database : 'irlelection2020'
    });
    connection.connect();
    next();
});

app.use('/api/parties', users);
app.use('/api/candidates', candidates);


module.exports = app;
var server = http.createServer(app);
server.listen(3000);
console.log("Server running on port 3000");

users.js(routes.js)

var express = require('express');
var router = express.Router();

/* GET candidates listing. */

router.get('/', function(req, res, next) {
    connection.query('SELECT * from parties', function (error, results, fields) {
        if(error){
            res.send(JSON.stringify({"status": 500, "error": error, "response": null})); 
            //If there is error, we send the error in the error section with 500 status
        } else {
            res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
            //If there is no error, all is good and response is 200OK.
        }
    });
});

router.get('/', function(req, res, next) {
    connection.query('SELECT * from candidates', function (error, results, fields) {
        if(error){
            res.send(JSON.stringify({"status": 500, "error": error, "response": null})); 
            //If there is error, we send the error in the error section with 500 status
        } else {
            res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
            //If there is no error, all is good and response is 200OK.
        }
    });
});




module.exports = router;

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {

        res.render('index', { title: 'Express' });
});

router.get('/candidates', function(req, res, next) {

    res.render('index', { title: 'Express' });
});


module.exports = router;

1 个答案:

答案 0 :(得分:0)

这里发生了几件事。对于以下代码:

var users = require('./routes/users');
var candidates = require('./routes/users');

仅仅因为您在命名这些不同的变量并不意味着在通过以下方式声明路线时发生任何魔术:

app.use('/api/parties', users);
app.use('/api/candidates', candidates);

两个端点都指向同一文件,并且将匹配它们遇到的第一个路由。在您的 users.js 文件中,您以完全相同的方式定义了两条路由:

router.get('/', function(req, res, next) {
// ...
router.get('/', function(req, res, next) {

因此,每当您访问/api/parties/api/candidates时,他们总是会从该文件中查找您的第一个路线。您基本上有两种选择:

  1. 制作两个单独的路由文件
  2. 更改声明路线的方式

对于方法1,您唯一要做的就是将候选代码从 users.js 移至新文件,例如 candidates.js ,然后进行更改定义:

var candidates = require('./routes/candidates');

对于方法2,您可以将它们保存在同一文件中,但必须将 app.js 中的基本路由更改为:

app.use('/api', users);

然后在users.js中,您将按照以下方式声明路由:

router.get('/parties', function(req, res) {
// ...
router.get('/candidates', function(req, res) {

您还希望将实际的路线功能更改为function(req, res),而不是function(req, res, next)。您也可以res.json来缩短JSON响应的时间:

res.send(JSON.stringify({"status": 200, "error": null, "response": results}));

res.json({"status": 200, "error": null, "response": results});