我的node.js表示路由有问题。我真的很陌生,我无法看到自己的错误。在请求localhost:2700 / api / subs时,我总是得到404错误,但我认为我的路线是正确的,不是吗?任何人都可以看到错误吗?
错误消息的开头:
Error: Not Found at ****/app.js:45:13 at Layer.handle [as handle_request] (****/node_modules/express/lib/router/layer.js:95:5)
以下是 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');
const mongoose = require('mongoose');
// establish connection to the Database
mongoose.connect('mongodb://localhost/test', {
useMongoClient: true
});
mongoose.connection.once('open', function() {
console.log('Connection to Database has been established..');
}).on('error', function(error){
console.log(error);
});
var index = require('./routes/index');
var users = require('./routes/users');
Subscriber = require('./routes/subscriber.js');
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('/', index);
app.use('/users', 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');
});
app.get('/api/subs', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
// ... here is a function which creates the database objects and saves
// them. took it out for better overview....
app.listen(2700, function(){
console.log("Listening on Port 2700")
});
module.exports = app;
和 subscriber.js 位于子目录中./routes:
const mongoose = require('mongoose');
var subscriberSchema = mongoose.Schema({
//seqnr shall go here. dunno how to declare integer x)
nr: Number,
name: String,
email: String,
uLink: String,
anwalt: String
});
var Subscriber = module.exports = mongoose.model('Subscriber', subscriberSchema);
//get Subscriber
module.exports.getSubscribers = function(callback, limit){
Subscriber.find(callback).limit(limit);
};
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;
答案 0 :(得分:2)
您需要在所有其他用途之后放置404 app.use
,否则它将忽略其之后的api/subs
。
此外,此位将永远不会运行,因为它也会在api.use
之后始终出现错误:
// 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');
});
另外,你真的不应该为404s抛出错误。它应告诉最终用户该页面不存在,但它不应该使您的脚本崩溃。
此外,我同意另一个答案,即你应该将这些代码块移动到单独的路由器文件中,但这对于良好的实践和结构来说比对这个特定的bug更有帮助。
答案 1 :(得分:1)
尝试将其放在一个单独的文件中,并将其包含在其他路线的位置,之前 404处理程序
app.use('/', index);
app.use('/users', users);
所以...制作subs.js
路线
var express = require('express');
var router = express.Router();
Subscriber = require('./routes/subscriber.js');
router.get('/', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
module.exports = router;
然后将其添加到您的app.js
var subs= require('./routes/subs');
...
api.use('/api/subs', subs);
...
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});