请求数据出错,无法有效的进行数据的请求,第一次配置,不知道咋回事。
import http_cfg from '../config/http_cfg';
import utils from ‘./utils’;
const host = http_cfg.HOST;
/**
-
通用的模拟请求工具
-
@param url 相对路径
-
@param data 数组
-
@param timeout 超时
-
@param method 方式
-
@param async 是否异步 默认true
-
@returns
*/
const http_request = function(url, data,method=“GET”,async=true) {
let xhr = new XMLHttpRequest() //创建XMLHttpRequest异步对象
let http_url = host+url;//拼接url
console.log(‘请求链接:’,http_url);
//resolve 返回正常数据 reject 返回error数据信息
return new Promise((resolve, reject) => {//设置超时时间 xhr.timeout = 10000; //单位毫秒 // 根据状态信息和状态码进行识别 xhr.onreadystatechange = ()=> { if (xhr.readyState == 4 && xhr.status == 200) { let result = xhr.responseText resolve(result) } } // get请求 if(method === 'GET'){ http_url = http_url+utils.converToUrl(data); xhr.open(method,http_url,async) xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8") xhr.send() } //post请求 if(method === 'POST'){ xhr.open(method,http_url,async) xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") xhr.send(data) } //错误处理 request 被停止时触发 xhr.onabort = () => { reject({ errorType: '被停止', xhr: xhr }) } //超过请求时间触发 xhr.ontimeout = () => { reject({ errorType: '超时', xhr: xhr }) } // request错误时触发 xhr.onerror = () => { reject({ errorType: "错误", xhr: xhr }) } return Promise;})
}
//声明称模块,在外部调用
export default http_request;