我正在使用快速节点js进行重定向项目。我只是快速节点js的初学者。 我不知道在哪里定义我的数据库逻辑。
目标: - 从数据库获取网址并重定向到该网址。
我的目录结构: -
app.js
controller
---------index.js
node_modules
package.json
public
------images
------stylesheet
------javascripts
routes
-----index.js
views
app.js
var express = require('express')
, http = require('http')
, mysql = require('mysql')
, path = require('path');
var app = express();
var controller = require('./controller')({app: app});
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 8888);
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(app.router);
app.get('/', function( req, res) {
res.render('index');
});
});
//connect to mysql database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxxx',
database : 'nodejsmysql'
});
connection.connect();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
控制器
function controller(param)
{
var app = param.app;
app.get('/id', function(request, response) {
var id= request.param("id");
// i need to use this id to fetch corresponding url from database and redirect that url.
});
}
module.exports = controller;
数据库查询: - 从db url
id='id';
答案 0 :(得分:1)
通常,您可以创建模型来处理数据库逻辑。一般模式是
例如,在routesX.js中你可能会有这样的东西:
var blogModel = require('./modelsX.js');
exports.blogAll = function(req, res) {
blogModel.getAll(function(data) {
res.render('someView', data);
});
}
在你的modelsX.js中你可能会有这样的东西:
exports.getAll = function(callback) {
// get data from the database here
// and call the callback
callback()
}
如果您想查看完整的端到端示例,请查看此回购:https://github.com/hectorcorrea/hectorcorrea.com/blob/master/routes/blogRoutes.js