【发布时间】:2016-07-09 11:56:49
【问题描述】:
正如标题所示,我正在尝试使用 Angular 的 $http 对象编写 AJAX 调用。我想发送一个在请求正文中提交 JSON 的 post 请求,但还有一个附加到 URL 的查询字符串。在通读了 $http 的文档、在 SO 上搜索答案并尝试了几种不同的配置后,我仍然不清楚如何正确传递参数。 目前,我的 API 响应为空 JSON 或错误请求 (400)。
代码
function inviteStaff (json) {
authToken = service.getAuthToken();
return $http({
method: 'POST',
url: baseUrl + '/invitations' + '?authToken=' + authToken,
data: JSON.stringify(json),
headers: {
'Content-type': 'application/json'
}
});
}
消费函数
self.invite = function ($form) {
self.showLoader = true;
InvitesService.inviteStaff($scope.inviteModel).then(function () {
$form.$setPristine();
$scope.inviteModel.timestamp = new Date();
$scope.invites.unshift($scope.inviteModel);
$scope.inviteModel = self.createNewInvite();
self.showLoader = false;
},
function () {
self.showLoader = false;
});
};
请求日志
data: "authToken=********&t=*****" // this is weird because it adds another "t" parameter to this query string here
headers: Object
Accept: "application/json"
Accept-Language: "en"
Content-type: "application/json"
authToken: "*********" // just the token here
__proto__: Object
method: "POST"
params: Object
timeout: Object
transformRequest: Array[1]
transformResponse: Array[1]
url: "http://****.****.com:****/doctors/invitations?authToken=*****"
__proto__: Object
参数 JSON 对象
{
accountType: "LEAD_DOCTOR",
firstName: "kraken",
lastName: "lastName",
email: "kraken@mail.com"
}
谁能解释一下这应该如何工作?我是否将 json 对象传递给数据或参数?我需要在数据字段上使用 JSON.stringify 吗?在某些情况下,我还看到人们将空字符串传递给数据。
我也一直通过 Charles Proxy 运行它。我可以非常接近我想要的,但由于某种原因,JSON 在 JSON 文本过滤器下显示为查询字符串,而不是 JSON 过滤器。
任何想法都会有所帮助。我将重构和升级它以使用 $resource 工具,但我们的最后期限很紧,我只想让这个工作现在。如果您需要更多信息,请告诉我。
更新 我们使用 swagger 来记录我们的 API,您实际上可以在他们的 UI 中点击端点。它产生以下 CURL 命令。我认为这可能有助于发现问题。
curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{
\"firstName\": \"string\",
\"lastName\": \"string\",
\"email\": \"blah@mail.com\",
\"accountType\": \"CLIENT\"
}" "http://*****.****.com:****/doctors/invitations?authToken=***obfuscatedAuthToken***"
【问题讨论】:
-
这到底是什么问题?
-
第二个问题:你可以传递整个javascript对象,Angular会处理它
-
@MB 我会更新问题
-
使用数据是正确的,参数用于变量和对象的数据。您不必对您的对象做任何事情,只需按原样传递它即可
-
你要把它传到哪里?您是否在 API 方面接受错误?
标签: javascript angularjs json ajax http