Der*_*nce 8 post http typescript
我正在尝试在Typescript中找到HTTP发布请求的示例,但只能找到使用Angular的示例。有人可以为我指出正确的方向,或者在此处发布使用JSON数据使用Post以获得响应JSON的简单示例。
如果要对HTTP POST请求使用TypeScript中的本机JavaScript函数,请查看YouMightNotNeedJQuery.com 上的JSON和POST示例。使用它,您可以实现自己的:
// Using callbacks:
function request<Request, Response>(
method: 'GET' | 'POST',
url: string,
content?: Request,
callback?: (response: Response) => void,
errorCallback?: (err: any) => void) {
const request = new XMLHttpRequest();
request.open(method, url, true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
// Success!
const data = JSON.parse(this.response) as Response;
callback && callback(data);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function (err) {
// There was a connection error of some sort
errorCallback && errorCallback(err);
};
if (method === 'POST') {
request.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
}
request.send(content);
}
// Using promises:
function request2<Request, Response>(
method: 'GET' | 'POST',
url: string,
content?: Request
): Promise<Response> {
return new Promise<Response>((resolve, reject) => {
request(method, url, content, resolve, reject);
});
}
Run Code Online (Sandbox Code Playgroud)
XMLHttpRequest 是内置的JavaScript类,并包含在TypeScript类型中。
这是我仅使用 Typescript 调用 GET 或 POST 的非常简单的示例。
//-------------------------------------------------
// Simple function to GET or POST
function httpCall(method: string, url:string, data:any, callback:(result:any)=>any) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (callback) xhr.onload = function() { callback(JSON.parse(this['responseText'])); };
if (data != null) {
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
}
else xhr.send();
}
Run Code Online (Sandbox Code Playgroud)
可选的输入数据(帖子正文)和回调。数据和结果都假定为 JSON。
| 归档时间: |
|
| 查看次数: |
18876 次 |
| 最近记录: |