angularjs 1.x:使用$ http.post发送{'key':undefined}

bit*_*its 3 http angularjs

我的要求是,我希望能够{title: "test", price: undefined}通过$ http.post从我的angular-app中将一个对象发送到我的nodejs应用程序(以便能够通过mongoDB中的Mongoose更新删除价格键)。

问题:

代码提取

console.log(object)
$http.post(url, object)
Run Code Online (Sandbox Code Playgroud)
  1. 在控制台中,我看到: {title: "test", price: undefined}
  2. 我的请求有效载荷包含 {title: "test"}

==>为什么我的有效载荷不包含完整的对象?如何添加价格:有效载荷中未定义?

sha*_*ncs 5

当HTTP请求Content-Typeapplication/json有效负载对象包含undefined某些字段的值时,这些字段将被删除。否则,服务器端程序将无法成功解析JSON- SyntaxError: Unexpected token u in JSON at position ...将会发生错误(令牌u只是“ undefined”的“ u”)。

这不是特定于Angular的行为,所有HTTP请求都应具有此逻辑。


Angular会发生什么$http.post

在Angular中,所有请求数据都将被转换。当数据为JSON时,toJSON(等于angular.toJson)将被调用以完成工作(源代码):

transformRequest: [function(d) {
  return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}]
Run Code Online (Sandbox Code Playgroud)

toJson()函数只是JSON.stringify源代码)的代理:

function toJson(obj, pretty) {
  if (isUndefined(obj)) return undefined;
  if (!isNumber(pretty)) {
    pretty = pretty ? 2 : null;
  }
  return JSON.stringify(obj, toJsonReplacer, pretty);
}
Run Code Online (Sandbox Code Playgroud)

JSON.stringify中

如果未定义,则在转换过程中会遇到函数或符号,则将其省略(当在对象中找到时)或将其检查为空(当在数组中找到时)。