res.json返回无意中修改的输入
My res.json function seems to be modifying my data. If I log the data in the function it returns the proper data. Only inside res.json does my data change and I can't figure out why.
我的res.json函数似乎正在修改我的数据。如果我在函数中记录数据,它将返回正确的数据。只有res.json里面的数据才会改变,我无法弄清楚原因。
For ex. Instead of returning {"unix":"1484600306","naturalFormat":"2017-01-16"}
it returns {"unix":"1484600306","naturalFormat":"\"2017-01-16\""}.
对于前者它返回{“unix”:“1484600306”,“naturalFormat”:“\”2017-01-16 }。
function:
function unixToDate(timestamp) {
var a = new Date(timestamp * 1000);
//console.log(a);
var rgx = /T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z/;
var newA = JSON.stringify(a);
//console.log(newA.replace(rgx, ""));
return newA.replace(rgx, "");
}
route
router.get('/:unix', function(req, res) {
var timestamp = req.params.unix;
var regex = new RegExp("\\d{10}");
if (regex.test(timestamp)) {
var date = unixToDate(timestamp);
console.log(date);
res.json({ unix : timestamp, naturalFormat : date });
} else {
res.json({ unix: null, naturalFormat : null});
}
});
Again i'm a newb with regex and if I had to guess it would have something to do with that.
再一次,我是一个正则表达式的新手,如果我不得不猜测它将与此有关。
PS I didn't use toString() because my date was coming out wrong i.e 11/30/2015 instead of 12/01/2015 so that's why I did it this way with regex.
PS我没有使用toString(),因为我的日期出错了,即2015年11月30日而不是2015年1月12日,所以这就是我用正则表达式这样做的原因。
Thank you!
1 个解决方案
#1
1
The problem is in unixToDate
, here:
问题出在unixToDate中,这里:
var newA = JSON.stringify(a);
You're serializing a Date as JSON, which means newA
will be a string like this: "2017-01-16T00:00:000.000Z"
, including the quotation marks. Then, when you call res.json
, it serializes that string again, quotation marks and all.
您将日期序列化为JSON,这意味着newA将是这样的字符串:“2017-01-16T00:00:000.000Z”,包括引号。然后,当你调用res.json时,它再次序列化该字符串,引号和所有。
The simplest fix is to use Date.prototype.toISOString
instead. It will return the same string as the above, without the quotation marks:
最简单的解决方法是使用Date.prototype.toISOString。它将返回与上面相同的字符串,不带引号:
var newA = a.toISOString();
In fact, your method of removing the time part of the date with String.prototype.replace
is a bit convoluted. ISO 8601 dates always have the same number of digits in each position, so why not just use String.prototype.slice
?
实际上,使用String.prototype.replace删除日期的时间部分的方法有点复杂。 ISO 8601日期在每个位置始终具有相同的位数,那么为什么不使用String.prototype.slice呢?
function unixToDate(timestamp) {
var date = new Date(timestamp * 1000);
return date.toISOString().slice(0, 10);
}
更多相关文章
- 11、javascript中字符串常用操作总结、JS字符串操作大全
- javascript如何取字符串中的数字
- 对象的属性也要加引号吗
- JavaScript中,提取子字符串方法:Slice、Substring、Substr的比较
- java 如何获取动态网页内容,返回字符串
- NodeJS - 解析JSON(只有字符串或数字)
- 如何在JavaScript中对字符串排序
- JSON.parse(xhr.responseText)意外的字符串错误
- 如何在url中将特殊字符作为查询字符串传递