带Typescript的http发布请求 [英] http Post request with Typescript

查看:1235
本文介绍了带Typescript的http发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

2020年更新:

请注意,到目前为止,全局fetch所有现代浏览器都可用,覆盖了95%的所有网络用户.如果您需要IE10或更低版本的支持,请阅读原始答案.

Update 2020:

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

MDN文档 | TypeScript定义

该功能在windowglobal上下文中可用的地方,如下所示:

Where the function is available in the window or global contexts, looks like:

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

因此您可以这样做:

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.
}

原始答案:

如果您想在TypeScript中对HTTP POST请求使用本机JavaScript函数,请查看 JSON 和 POST 示例.使用它,您可以实现自己的:

Original Answer:

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

// 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);
    });
}

XMLHttpRequest是内置的JavaScript类,包含在TypeScript类型中.

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

这篇关于带Typescript的http发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆