我是express.js編碼的新手。在我的代碼中,我想訪問兩個URL,如http://localhost:3000和http://localhost:3000/fetch,以使用get方法提供不同的請求。雖然訪問第一個URL我能夠得到響應,但訪問第二個URL時,我得到404錯誤。我無法弄清楚這個問題,你能幫我解決這個問題嗎?在expressjs代碼中獲取無效的URL消息
下面是我的文件:
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 index = require('./routes/index');
var fetch = require('./routes/fetch');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/fetch',fetch);
app.use('/', index);
// 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: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('SmartBin: Invalid URL');
err.status = 404;
next(err);
});
modules.export=app;
index.js
var express = require('express');
/* GET home page */
module.exports = (function() {
var path = require('path');
var bodyParser = require('body-parser');
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
var router = express.Router();
router.get('/', function(req, res, next) {
//res.render('index', { title: 'Express' });
db.get('devicereg',{}).then(function(v){
//for (i=0; i<v.length-1; i++)
//res.json(v[i]);
res.json(v);//.end();
}).catch(function(v){
console.log('[SmartBin:Error ' + v);
});
});
return router;
})();
fetch.js
var express = require('express');
/* GET home page. */
module.exports = (function(){
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var db = require('./dbclient');
db.dbconnection(null,null,null,null,'smartbin',null);
router.get('/fetch', function(req, res, next) {
db.get('devicereg',{}).then(function(v){
res.json(v);
}).catch(function(v)
{console.log('[SmartBin:Error ' + v);}
);
});
return router;
})();