Set X-Requested-With header and add HttpError (#623)
This commit is contained in:
parent
f21f5039b2
commit
ed6badbabe
|
|
@ -1,3 +1,5 @@
|
||||||
|
import { HttpError } from "./HttpError"
|
||||||
|
|
||||||
export interface IHttpClient {
|
export interface IHttpClient {
|
||||||
get(url: string, headers?: Map<string, string>): Promise<string>;
|
get(url: string, headers?: Map<string, string>): Promise<string>;
|
||||||
options(url: string, headers?: Map<string, string>): Promise<string>;
|
options(url: string, headers?: Map<string, string>): Promise<string>;
|
||||||
|
|
@ -22,6 +24,7 @@ export class HttpClient implements IHttpClient {
|
||||||
let xhr = new XMLHttpRequest();
|
let xhr = new XMLHttpRequest();
|
||||||
|
|
||||||
xhr.open(method, url, true);
|
xhr.open(method, url, true);
|
||||||
|
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
|
||||||
|
|
||||||
if (headers) {
|
if (headers) {
|
||||||
headers.forEach((value, header) => xhr.setRequestHeader(header, value));
|
headers.forEach((value, header) => xhr.setRequestHeader(header, value));
|
||||||
|
|
@ -33,19 +36,13 @@ export class HttpClient implements IHttpClient {
|
||||||
resolve(xhr.response);
|
resolve(xhr.response);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
reject({
|
reject(new HttpError(xhr.statusText, xhr.status));
|
||||||
status: xhr.status,
|
|
||||||
statusText: xhr.statusText
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
xhr.onerror = () => {
|
xhr.onerror = () => {
|
||||||
reject({
|
reject(new HttpError(xhr.statusText, xhr.status));
|
||||||
status: xhr.status,
|
}
|
||||||
statusText: xhr.statusText
|
|
||||||
});
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
export class HttpError extends Error {
|
||||||
|
statusCode: number;
|
||||||
|
constructor(errorMessage: string, statusCode: number) {
|
||||||
|
super(errorMessage);
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue