【问题标题】:Angular convert $http.post to XHRAngular 将 $http.post 转换为 XHR
【发布时间】:2017-04-28 21:31:18
【问题描述】:

我想做一些上传并获得进度反馈。

我曾经做过的事情(在观察进展之前):

$http.post(BASE_URL, formData, {
withCredentials: true,
transformRequest: angular.identity,
params: {'context': context}
})

我尝试转换为:

var xhrObj = new XMLHttpRequest();
xhrObj.upload.addEventListener("progress", progressFunction, false);
xhrObj.open("POST", BASE_URL, true);
xhrObj.withCredentials = true;
xhrObj.setRequestHeader("Content-type", fileItem.file.type);
xhrObj.setRequestHeader("X_FILE_NAME", fileItem.file.name);
xhrObj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhrObj.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
xhrObj.setRequestHeader("Pragma", "no-cache");
xhrObj.setRequestHeader("Expires", "0");
//xhrObj.setRequestHeader("Access-Control-Allow-Credentials", "false");
xhrObj.send(fd);

但是好像凭证没有通过,我该怎么办?

【问题讨论】:

  • 确定fd 有数据吗?
  • 是的,我刚刚使用文件创建了 if(当我发送 XHR 时),我在请求有效负载中获得了内容
  • 控制台有错误吗?
  • 不是真的,我看到:(失败)net::ERR_CONNECTION_RESET 在 http 请求的 chrome 状态中。浏览器不提供身份验证(cookies ...)。 (好像 withCredentials 没被理解)
  • 看来我们可以做到多亏了eventHandlers并保留了原始的$http.post,去试试吧。

标签: angularjs xmlhttprequest


【解决方案1】:

好吧,所以不需要手动操作!

从 Angular 1.5.4(以及 1.5.5 中的一些错误修复)开始,您可以使用 eventHandlers 和 uploadEventHandlers。

见:https://code.angularjs.org/1.6.4/docs/api/ng/service/$http

那么就这样做吧:

$http.post(BASE_URL, formData, {
withCredentials: true,
transformRequest: angular.identity,
params: {'context': context},
uploadEventHandlers: {
  progress: function(event) {//Add whatever you want to do}
}
})

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2017-07-04
    • 2020-07-12
    相关资源
    最近更新 更多