获取API不会返回XMLHttpRequest

时间:2017-05-31 08:23:20

标签: javascript ecmascript-6 fetch-api

我想转换XMLHttpRequest函数来获取API。但结果却不同。

我有些事情要做错,但我不知道:/

我对XMLHttpRequest的承诺:

  return new Promise(function (resolve, reject) {

    let formData = new FormData($searchForm);

    if (searchTerm.length) {
      formData.append("search", searchTerm);
    }

    let request = new XMLHttpRequest();

    request.onreadystatechange = function () {
      if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
        console.log(request);
        resolve(request.responseText);
      }
    };

    request.open($searchForm.method, $searchForm.action, true);
    request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    request.send(formData);

  });

返回(我想要的):

  

XMLHttpRequest {onreadystatechange:   reload / http:// localhost:3000 / app_dev.php / r ...",status:200,statusText:" OK",   responseType:"",响应:" {" countMessage":"没有找到产品" }

我的功能获取API

function searchReload() {

  const formData = new FormData($searchForm);
  const url = $searchForm.action;
  const method = $searchForm.method;

  if (searchTerm.length) {
    formData.append('search', searchTerm);
  }

  const header = new Headers();
  header.append('X-Requested-With', 'XMLHttpRequest');

  return fetch(url, {
    method: method,
    header,
    body: formData
  }).then(function (response) {
    return response;
  });

}

searchReload()
  .then(response => {
    return console.log(response);
  });

此函数返回:

  

回复{type:" basic",url:" http://localhost:3000/app_dev.php/r ...",   重定向:false,status:200,ok:true,statusText:" OK",headers:   标题,正文使用:false}

任何人都可以帮助我吗?我不知道问题是什么,为什么我无法做出回复:" {" countMessage":"没有找到产品" } 我的回答:(

谢谢社区!

1 个答案:

答案 0 :(得分:1)

您需要致电response.json()来阅读正文:

return fetch(url, {
  method: method,
  header,
  body: formData
}).then(function (response) {
  // perhaps check the status before doing this!
  return response.json();
});

以下示例,当您阅读正文时bodyUsed会发生什么

fetch('https://jsonplaceholder.typicode.com/posts/1').then(function(response) {
    console.log(response.bodyUsed);
    var res = response.json();
    console.log(response.bodyUsed);
    return res;
}).then(function(json) {
    console.log(json)
});