【问题标题】:XHR Request : UnhandledPromiseRejectionWarning: Unhandled promise rejectionXHR 请求:UnhandledPromiseRejectionWarning:未处理的承诺拒绝
【发布时间】:2018-09-14 20:06:46
【问题描述】:

我尝试使用 xhr 方法向 instagram 发出请求以检查我的登录名/密码,但我收到以下错误消息:

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1)

我想知道为什么以及如何改进我的代码。非常感谢。

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

【问题讨论】:

  • 您可以将.catch 链接到您的new Promise 以处理拒绝

标签: node.js xmlhttprequest


【解决方案1】:

您收到该消息是因为在您的 Promise 的函数中引发了错误,或者因为您正在点击 reject('bad password') 行。如果您一直收到该错误消息,则可以在 promise 的末尾添加一个 catch,如下所示:

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

然后您应该会收到更有用的错误消息。

即使您没有始终如一地重现该错误消息,您仍然应该添加一个 catch 无论如何。

【讨论】:

  • 非常感谢@戴帽子的家伙 :) 我收到此错误消息:ReferenceError: window is not defined
  • @AmauryLeproux 在浏览器中,window 指的是页面的全局对象。 Node.js 没有window,所以window._sharedData.config.csrf_token 不存在。我不知道如何解决这个问题,所以请自行解决,或者为它打开另一个问题。
  • 您知道如何在浏览器上使用它吗?因为现在我得到“window.sharedData”没有定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多