angularjs 1.x:使用$ http.post发送{'key':undefined} [英] angularjs 1.x: send {'key' : undefined} with $http.post
问题描述
我的要求是我希望能够通过$ http从我的angular-app发送一个像 {title:test,price:undefined}
这样的对象。发布到我的nodejs应用程序(能够通过我的mongoDB中的Mongoose更新删除价格键)。
My requirement is that I want to be able to send an object like {title: "test", price: undefined}
from my angular-app via $http.post to my nodejs app (to be able to delete the price key via Mongoose update in my mongoDB).
问题:
代码提取
console.log(object)
$http.post(url, object)
- 在控制台中,我看到:
{title :test,price:undefined}
- 我的请求有效负载包含
{title:test}
- In the console, I see:
{title: "test", price: undefined}
- My request payload contains
{title: "test"}
==>为什么我的有效载荷不包含完整的对象?如何在我的有效负载中添加价格:未定义?
==> Why doesn't my payload contain the full object? How can I add the price: undefined in my payload?
推荐答案
当HTTP请求 Content-Type
是 application / json
,有效负载对象包含 undefined
作为某些字段的值,这些字段将被删除。否则,服务器端程序将无法成功解析JSON - 错误语法错误:位于JSON位置的意外令牌u
将发生(令牌 u
只是未定义的u。
When HTTP request Content-Type
is application/json
and the payload object contains undefined
as some fields' value, those fields will be removed. Otherwise, server side program won't be able to parse the JSON successfully -- an error SyntaxError: Unexpected token u in JSON at position ...
will happen (the token u
is just the "u" of "undefined").
这不是Angular特定行为,所有HTTP请求都应具有此逻辑。
This is not an Angular specific behaviour, all HTTP requests should have this logic.
Angular的 $ http.post
会发生什么?
What happens in Angular's $http.post
?
在Angular中,所有请求数据将被改造。当数据为JSON时,将调用 toJSON
(等于 angular.toJson
)来完成工作(< a href =https://github.com/angular/angular.js/blob/master/src/ng/http.js =nofollow noreferrer>源代码):
In Angular, all request data will be transformed. When the data is JSON, toJSON
(which equals to angular.toJson
) will be invoked to do the job (source code):
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}]
toJson()
function只是 JSON.stringify
的代理(源代码):
The toJson()
function is just a proxy to JSON.stringify
(source code):
function toJson(obj, pretty) {
if (isUndefined(obj)) return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
在 JSON.stringify :
如果未定义,在转换过程中遇到函数或符号,则省略(当在对象中找到它时)或者删除为null(当它在数组中找到时) )。
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).
这篇关于angularjs 1.x:使用$ http.post发送{'key':undefined}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!