0

我正在使用 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;
4

1 回答 1

0

所以经过一些研究,我想我知道发生了什么。通过搜索堆栈溢出,使用我标记我的问题的标签,我想出了这个: https ://expressjs.com/en/guide/routing.html#route-parameters 路由器的文档。如果我没看错的话,基本上就是说我需要在每个连字符后添加一个新的路由参数。

所以 fetch 调用

dateOfLastBroadcastNeeded = moment(dateOfLastBroadcastNeeded).format('MM-DD-YYYY');
fetch('/recentbroadcasts/'+ dateOfLastBroadcastNeeded)

需要一个查找 3 个参数的路由器,如下所示:

router.get('/recentbroadcasts/:month-:date-:year', function (req, res) {

我会尝试一下,如果它不起作用,我会回到这里并删除这个答案。否则,我会将这个答案留给遇到同样问题的其他人。

于 2018-12-18T18:19:35.920 回答