XMLHttpRequest在检查器中返回响应,但在访问时返回null

时间:2017-05-11 15:56:17

标签: reactjs xmlhttprequest

我有以下功能:

var submit = (event) => {
    event.preventDefault();
    var xhr = new XMLHttpRequest();
    var url = '*removed*';
    xhr.open('POST', url, true);
    xhr.responseType = "json";
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
    console.log(xhr); 
}

一切正常,我得到了我预期的回应。这是回应(简称):

readyState: 4

response: {token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkI…DQxfQ.s4Py_lmVK1-Ji9F573ZFddtpdnb2qa1ETHHluG11l44"}

responseType: "json"

status: 200

statusText: "OK"

我需要获取“响应”字段中包含的令牌以供将来请求使用。问题是,如果我调用xhr.response,它会显示“null”。无论我如何调用返回的对象的任何单个元素,我都无法访问它们。

1 个答案:

答案 0 :(得分:1)

我最后一次使用XMLHttpRequest时,我记得它有一个onreadystatechange事件,一旦异步调用完成就会触发,你必须为其编写处理程序,以便从http调用中访问响应

进一步阅读mozilla docs

submit = (event) => {
  event.preventDefault();
  var xhr = new XMLHttpRequest();
  var url = '*removed*';
  xhr.open('POST', url, true);
  xhr.responseType = "json";
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.onreadystatechange = function(){
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          console.log(xhr.responseText);
      }
  }
  xhr.send(JSON.stringify({ email: this.state.email, password: this.state.password }));
}