使用 Typescript 的 http Post 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49014689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:52:35  来源:igfitidea点击:

http Post request with Typescript

typescripthttppost

提问by Derek Lawrence

I am trying to find an example of HTTP post request in Typescript but can only find examples that use Angular. Could someone point me in the right direction to find this or post a quick example here of using Post with JSON data to get a response JSON.

我试图在 Typescript 中找到 HTTP post 请求的示例,但只能找到使用 Angular 的示例。有人可以指出我正确的方向来找到这个或在这里发布一个快速示例,使用带有 JSON 数据的 Post 来获取响应 JSON。

采纳答案by EyasSH

Update 2020:

2020 年更新:

Note that as of now, the global fetchis available on all modern browsers and covers 95% of all web users. If you need support for IE10 or before, read the original answer.

需要注意的是,截至目前,全球fetch适用于所有现代浏览器和覆盖所有互联网用户的95% 。如果您需要对 IE10 或更早版本的支持,请阅读原始答案。

MDN Doc| TypeScript Definition

MDN 文档| 打字稿定义

Where the function is available in the windowor globalcontexts, looks like:

该函数在windowglobal上下文中可用的地方,看起来像:

    fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

so you can do:

所以你可以这样做:

const response = await fetch(myUrl, {
  method: 'POST',
  body: content,
  headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} });

if (!response.ok) { /* Handle */ }

// If you care about a response:
if (response.body !== null) {
  // body is ReadableStream<Uint8Array>
  // parse as needed, e.g. reading directly, or
  const asString = new TextDecoder("utf-8").decode(response.body);
  // and further:
  const asJSON = JSON.parse(asString);  // implicitly 'any', make sure to verify type on runtime.
}

Original Answer:

原答案:

If you want to use native JavaScript functions in TypeScript for your HTTP POST request, take a look at the JSONand POSTexamples on YouMightNotNeedJQuery.com. Using that, you can implement your own:

如果您想在 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);
    });
}

XMLHttpRequestis a built-in JavaScript class and included in the TypeScript typings.

XMLHttpRequest是一个内置的 JavaScript 类并包含在 TypeScript 类型中。

回答by John Henckel

Here is my very simple example to call GET or POST with Typescript only.

这是我仅使用 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();
}

Optional input data (the post body) and callback. The data and result are both assumed to be JSON.

可选的输入数据(帖子正文)和回调。数据和结果都假定为 JSON。

回答by Arun Kumar

Sending form data.

发送表单数据。

Save(model: yourmodalarray[]): Observable<any> {

        var formData: FormData = new FormData();

        formData.append('id', '');
 const headers = new Headers({
            'Accept': 'application/json',
            'enctype': 'multipart/form-data'
        });
        const options = new RequestOptions({ headers: headers });


        return this._http
            .post(this._baseUrl + 'Save', formData, options)
            .map(res => <any>res.json())
            .catch(this.handleError);

    }