我正在使用 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();
有人知道这里发生了什么吗?
最佳答案
我想通了。事实证明,正在发出第二个 favicon.ico 请求,这导致了错误,因为显然“favicon.ico”不是有效的时间值
关于javascript - 错误消息 'RangeError: Invalid time value' 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658706/