Response.json没有显示带有值的字段 undefined
我正在实现一个节点api,以操纵Mongo数据库中的数据。查询使我享有权利JSON
。当我将其发送JSON
到React客户端时,包含的字段undefined
不会显示。我究竟做错了什么?有解决方法吗?
为了缩小问题的范围,请将以下代码添加到节点服务器。在console.log
将打印右输出。例如status: undefined
,它将包括,但res.json
将不包括具有value的任何节点undefined
。
app.get("/test", function(req, res) {
let test = {
document: "test",
data: {
products: [
{
id: 123,
type: "smartphone",
name: "Motorola Moto G",
instock: true,
status: undefined,
link: null
},
{
id: 456,
type: "notsosmartphone",
name: "Samsung S7",
instock: false,
status: "burning",
link: undefined
}
],
length: 2,
date_created: '20161015T09:15',
status: undefined,
person: {name: "Kathy", age: 30, cute: true},
arr:[123,"abc",{"a":"1"},{"b":"2"},{"c":"3"}]
}
};
console.log(test);
res.json(test);
});
Expressjsresponse.json()
方法使用JSJSON.stringify()
方法将对象转换为JSON字符串。
JSON.stringify()
显式地undefined
从调用对象中移除值,因为undefined
这不是有效的JSON值类型。
您可以使用一个replacer
函数来显式覆盖undefined
行为并将其设置为null
,以便在响应中返回它们。
例:
app.set('json replacer', function (key, value) {
// undefined values are set to `null`
if (typeof value === "undefined") {
return null;
}
return value;
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句