Search code examples
angularjsxmlhttprequest

Angular convert $http.post to XHR


I'd like to do some upload and get so progress feedback.

What i used to do (before to watch for progress):

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

I tried to convert to:

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);

But it seems credentials are not passed, how should i do ?


Solution

  • Well, so no need to do it manually !

    Since angular 1.5.4 (and some bugfixes in 1.5.5), you can use eventHandlers and uploadEventHandlers.

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

    So simply do that:

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