我正在使用 Node.js 和 Express,但收到一条错误消息:
加载资源失败:服务器响应状态为 404(未找到)[ http://localhost:3000/recentbroadcasts/12-10-2018]
它工作正常,然后我尝试向 url 添加一个日期参数,然后我开始收到 404。我错过了什么?
下面是来自网页、app.js 和路由器文件的代码。
我将路线从/recentBroadcasts 更改为/recentbroadcasts/:date以尝试获取一些信息来调用我的数据库。然后我开始收到错误。
我必须做一些特别的事情才能使用路由参数吗?谢谢
从网页 Javascript 调用的路由
let getRecentBroadcasts = function (lengthOfBroadcastHistoryNeeded) {
lengthOfBroadcastHistoryNeeded+=7;
let dateOfLastBroadcastNeeded = moment().subtract(lengthOfBroadcastHistoryNeeded, 'days').calendar();
dateOfLastBroadcastNeeded = moment(dateOfLastBroadcastNeeded).format('MM-DD-YYYY');
fetch('/recentbroadcasts/'+ dateOfLastBroadcastNeeded)
.then(response => response.json())
.then(recentBroadcastsJson => {
broadcastListData = recentBroadcastsJson;
populateRecents();
})
.catch(error => {
console.log(error)
});
};
app.js 文件
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let bodyParser = require('body-parser');
let indexRouter = require('./routes/index'); let usersRouter = require('./routes/users');
let app = express();
app.locals.moment = require('moment');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req, res, next) { req.db = db; next(); });
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) { next(createError(404)); });
module.exports = app;
index.js 文件
let express = require('express');
let router = express.Router();
router.get('/recentbroadcasts/:date', function (req, res) {
let db = req.db; let collection = db.get('broadcastCollection'); let historyNeeded = req.params.date;
let a = moment(historyNeeded);
let b = moment().date();
let daysOfHistory = a.diff(b, 'days');
let dbQuery = { "broadcastAirDate": { $gte: new Date((new Date().getTime() - (daysOfHistory * 24 * 60 * 60 * 1000))), $lte: new Date((new Date().getTime())) } };
collection.find(dbQuery, {}, function (e, docs) {
let sortedBroadcastData = docs.sort(sortDesc("broadcastAirDate"));
res.json(sortedBroadcastData); }); });
module.exports = router;