出现错误信息“RangeError: Invalid time value”的奇怪行为

3

我正在使用Express编写一个简单的时间戳API。基本上,当用户输入“普通”格式的日期时,将显示一个带有Unix格式和普通格式的JSON对象。这是我的代码的相关部分:

timeRouter.route('/:time')
  .get((req, res, next) => {
    let time = req.params.time;
    let unixTime = Number(time);

    if (unixTime) {
      res.json({'unix': unixTime, 'natural': moment.unix(unixTime).format('MMMM D, YYYY')});
    } else {
      let timeDate = new Date(time);
      console.log(`timeDate: ${timeDate}`);
      let isoTimeDate = timeDate.toISOString();
      console.log(`isoTimeDate: ${isoTimeDate}`);
      if (moment(isoTimeDate).isValid()){
        res.json({'unix': Number(moment(isoTimeDate).format('X')), 'natural': moment(isoTimeDate).format('MMMM D, YYYY')});
      } else {
        res.json({'unix': null, 'natural': null});
      }
    }
  });

如果我输入URL“localhost:3000/January 10 2015”,API会按预期工作并返回以下结果:
{
  "unix": 1421712000,
  "natural": "January 20, 2015"
}

问题在于我在控制台中得到了以下内容:

timeDate: Tue Jan 20 2015 00:00:00 GMT+0000 (UTC)

isoTimeDate: 2015-01-20T00:00:00.000Z

timeDate: Invalid Date

RangeError: Invalid time value

at /app/routes/timeRouter.js:19:34

at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)

at next (/app/node_modules/express/lib/router/route.js:137:13)

at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)

at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)

at /app/node_modules/express/lib/router/index.js:281:22

at param (/app/node_modules/express/lib/router/index.js:354:14)

at param (/app/node_modules/express/lib/router/index.js:365:14)

at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3)

at next (/app/node_modules/express/lib/router/index.js:275:10)

前两行的输出结果非常清晰,因为这是代码中两个console.log语句的结果。奇怪的是,在此之后,变量timeDate再次被记录到控制台,但此时其值为无效日期,并导致了错误消息。第19行代码是:let isoTimeDate = timeDate.toISOString();有人知道这里发生了什么吗?

1
可能有助于指出app/routes/timeRouter.js中的第19行是哪一行。 - mscdex
此外,在调用 new Date(time) 之前,您应该记录 time 的值,以查看传递给 Date 构造函数的确切内容。 - mscdex
@mscdex 谢谢,我已经编辑过了,包括哪一行是第19行的信息。 - avatarhzh
1个回答

0
我找到了答案。原来是因为发出了第二个favicon.ico请求,这导致了错误,因为显然'favicon.ico'不是一个有效的时间值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接