【问题标题】:NodeJS Is it possible to run multiple sql queries in a single routes page?NodeJS 是否可以在单个路由页面中运行多个 sql 查询?
【发布时间】:2020-04-21 21:28:20
【问题描述】:

我正在尝试使用 NodeJS 从 mysql 数据库中提取数据。我需要运行多条路线,但是否可以在一个 routes.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;

【问题讨论】:

  • 您的目标是使用一个路由文档(在您的示例中为users.js) - 当请求的路径为/api/parties 时,您的SELECT * from parties 查询将运行,但当请求的路径为@ 987654327@ 你的SELECT * from candidates 查询会运行吗?

标签: mysql node.js database express


【解决方案1】:

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

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});

【讨论】:

  • 所以在这一切之后,我将能够搜索例如“localhost:3000/api/candidates and the same“party”,它会显示不同的数据?
  • 我不确定你在问什么。如果您想使用相同的路线来显示来自不同政党的候选人,您可能需要执行/api/:partyId/candidates 之类的操作,然后根据该 ID 修改您的 SQL 查询。您可以在此处查看 Express 路由文档:expressjs.com/en/guide/routing.html
  • 完美,成功了,它的完美运行非常有帮助,非常感谢。
猜你喜欢
  • 2020-02-11
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多