【发布时间】: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