Search code examples
node.jsxmlhttprequest

XHR Request : UnhandledPromiseRejectionWarning: Unhandled promise rejection


I try to make a request to instagram to check my login / password using xhr method but I get this error message:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

I'd like to know why and how I can improve my code. thank you very much.

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var params = "username=username&password=password";
var CSRF_HEADER = 'X-CSRF-Token';

new Promise(function (resolve, reject) {

 var http = new XMLHttpRequest();

 http.open("POST", "https://www.instagram.com/accounts/login/ajax/", 
 true);
 http.setRequestHeader('x-csrftoken', 
 window._sharedData.config.csrf_token);
 http.setRequestHeader('x-instagram-ajax', '1');
 http.setRequestHeader('x-requested-with', 'XMLHttpRequest');
 http.setRequestHeader("pragma", "no-cache");
 http.setRequestHeader("cache-control", "no-cache");
 http.setRequestHeader("accept-language", "en-US,en;q=0.8,it;q=0.6");
 http.setRequestHeader("content-type", "application/x-www-form- 
 urlencoded");

 http.onreadystatechange = function () {
 if (http.readyState == 4 && http.status !== 200) {
   reject('error: ' + http.status);
 };
 if (http.readyState == 4 && http.status == 200) {
   var json = JSON.parse(http.response);
   if (!json.authenticated) {
     reject('bad password');
   } else if (json.authenticated && json.user && json.status === 'ok') 
   {
     resolve('success:', document.cookie);
   };
  };
 };

 http.send(params);
});

Solution

  • You are getting that message because an error was thrown inside your Promise's function, or because you are hitting the reject('bad password') line. If you are consistently getting that error message, you can add a catch to the end of the promise like so:

    new Promise(function (resolve, reject) {
        ...
    }).catch(function (error) {
        console.log(error);
    });
    

    You should then get a more helpful error message.

    And even if you don't consistently reproduce that error message, you should still probably add a catch anyways.