我有ASP.NET背景。我试图在ASP.NET中使用MVC逻辑来理解Node.js的“路由”逻辑。例如在我的global.js中,有一个对/ users / userlist的AJAX调用(我不知道它是什么,它是MVC中的控制器)。我正试图使用下面的代码到达那个控制器,但我明白了:
获取http://localhost:3000/users/userlist 404(未找到)
我该怎么做才能摆脱这个?感谢。
这是app.js(完整):
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest2');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', index);
app.use('/userlist', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
这是users.js(完整):
var express = require('express');
var router = express.Router();
/*
* GET userlist.
*/
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('userlist');
collection.find({},{},function(e,docs){
res.json(docs);
});
});
module.exports = router;
这是global.js:
$.getJSON( '/users/userlist', function( data ) {
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td><a href="#" class="linkshowuser" rel="' + this.username + '">' + this.username + '</a></td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#userList table tbody').html(tableContent);
});
这是index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
当我运行此代码时,我得到了这个:
获取http://localhost:3000/users/userlist 404(未找到)
答案 0 :(得分:0)
将所有代码i app.js
包含在以下行中var express = require('express');
var app = express();
// other code below