关于前端http请求timeout总结

  • xmlhttprequest
let xhr = new XMLHttpRequest();

xhr.timeout = 120000 ;  // 单位ms
xhr.ontimeout = (e)=> {
  console.log(e)//超时回调函数
};

xhr.open('GET', '/server', true);
xhr.send(null);
xhr.onreadystatechange = ()=>{
    if(xhr.status === 4 && xhr.readyState == 200){
        console.log(xhr.responseText);
   }
 };
  • angularJs
$http.get({ url: url, timeout: 120000 }).success(data)=>{})
  • angular2+
	import { Http, Headers } from '@angular/http';
	import { Observable } from 'rxjs/Observable';
	
    post(url: string, params?: any): Observable {
        let headers = new Headers();
        headers.append("Content-Type", "application/json;charset=utf-8");
        return this.http.post(url, params, { headers: headers })
        				.timeout(120000 )   //单位ms
            			.map(response => response.json());
    }
  • vue
export default {
    post(url, params) {
        return axios.post(url, params, { timeout: 120000 });  //单位ms
    }
 }
  • 总结
    其实各大框架http服务都是对xmlhttprequest的封装,原理都是一样的。

你可能感兴趣的:(关于前端http请求timeout总结)