leohxj
8/9/2017 - 10:56 AM

fetch-cors-post.js

corsFunc(params) {
    const headers = new Headers({
      'Content-Type': 'application/json',
      Accept: 'application/json',
    });

    return fetch('xxxxxx', {
      method: 'post',
      headers,
      mode: 'cors',
      credentials: 'include',
      body: JSON.stringify(params),
    }).then((response) => {
      // 处理网络错误
      if (response.status >= 200 && response.status < 300) {
        return response.json();
      }
      const error = new Error(response.statusText);
      error.response = response;
      error.type = 'statusError';
      throw error;
    }).then((data) => {
      // 对接口数据的
      const { success, content } = data;
      const result = success;

      if (result) {
        return content;
      }
      const error = new Error('Not the expected results');
      error.type = 'dataError';
      error.response = data;
      throw error;
    }).catch((e) => {
      throw e;
    });
  }