带Typescript的http发布请求

Der*_*nce 8 post http typescript

我正在尝试在Typescript中找到HTTP发布请求的示例,但只能找到使用Angular的示例。有人可以为我指出正确的方向,或者在此处发布使用JSON数据使用Post以获得响应JSON的简单示例。

Eya*_*sSH 7

如果要对HTTP POST请求使用TypeScript中的本机JavaScript函数,请查看YouMightNotNeedJQuery.com 上的JSONPOST示例。使用它,您可以实现自己的:

// 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类型中。

  • 我在发送之前也添加了此内容。`for(让标题的标题){request.setRequestHeader(header.key,header.value); }`然后添加了一个参数来请求`headers:Array &lt;{key:string,value:string}&gt;,` (2认同)

Joh*_*kel 5

这是我仅使用 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。