Response.json不显示值未定义的字段

彼得·舒尔茨

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);
});
费利佩·萨比诺(Felipe Sabino)

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TypeError:res.response未定义

角度未定义Response.success

Dingo api $response 未定义

API在HTML中显示未定义,而不显示值

调用Laravel5中未定义的方法Illuminate \ Http \ Response :: json()

如果axios请求失败,则error.response未定义

在catch axios中未定义error.response

为什么response.data是未定义的?

类型错误:response.data 未定义

未定义的变量:$ http_response_header

TypeError:在ajax中未定义response [idx]

用户未定义但 response.data 不是

Spring Rest Api Json Response不显示属性名称

动态字段JS值显示“未定义”

在HTML视图中不显示数据(仅显示“未定义”的数据值)

json查询响应值显示未定义

WordPress的prettyphoto灯箱不显示标题。显示未定义

字段的jQuery值未定义

为什么response.chartAt(0)在我的AJAX调用中返回未定义?

为什么从Youtube Data Api 3中“ response.result未定义”?

Rails 5控制器中未定义的方法response_to

为什么会出现错误:“错误:未定义Render_to_response”;Django的

未定义的局部变量或带有response_with的方法(Ruby on Rails)

邮递员:TypeError:无法读取未定义的属性“ Response”

由 response.download() 响应的文件并下载为包含未定义的 blob

[未处理的承诺拒绝:类型错误:未定义不是对象(评估'response.data')]

从存储在 vuex 中的 axios 获取未定义的 response.data

react-native-image-picker response.uri 未定义

从Json Response填充NSMutableArray