I log in to the site from IE. How to download a file through the browser console? I try the next snippet - an error is issued. In fact, the action of the js code is similar to saving the file manually. It feels like js-downloads on its own and not using browser cookies.

https://www.gosuslugi.ru/api/lk/v1//orders/428297648/history/1083114266/files/SUxT/download 401 (Unauthorized) 

...

 function download(url, fileName) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onprogress = function(event) { if (event.lengthComputable) { var percentComplete = (event.loaded / event.total)*100; //yourShowProgressFunction(percentComplete); } }; xhr.onload = function(event) { if (this.status == 200) { _saveBlob(this.response, fileName); } else { //yourErrorFunction() } }; xhr.onerror = function(event){ //yourErrorFunction() }; xhr.send(); } function _saveBlob(response, fileName) { if(navigator.msSaveBlob){ //OK for IE10+ navigator.msSaveBlob(response, fileName); } else{ _html5Saver(response, fileName); } } function _html5Saver(blob , fileName) { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); document.body.removeChild(a); } 
  • What mistake then? What does not work? - programmer403
  • @ programmer403 401 (Unauthorized). This is such a mistake. - Axixa Timano

1 answer 1

What is 401 error:

The HTTP 401 Unauthorized client error status response code indicates that the request was not applied because it lacks valid credentials for the target resource.

That is, the file you want to receive is blocked by the resource. he thinks that you are an unauthorized user, anonymous.

You need to transfer the authorization data in the Header (Request Header). XMLHttpRequest.setRequestHeader() method

xhr.setRequestHeader('Authority', '_ТОКЕН_АВТОРИЗАЦИИ');

  • Thanks for the answer) But how to download the "browser"? After all, you can say - the browser, well, well. Download this file with your cookies and headers - Axixa Timano
  • @AxixaTimano javascript cannot set cookies in request headers, for security reasons) - programmer403