我试图在Typescript中找到HTTP post请求的示例,但只能找到使用Angular的示例.有人能告诉我找到这个的正确方向吗?或者在这里发布一个使用post和JSON数据获取JSON响应的快速示例.
我试图在Typescript中找到HTTP post请求的示例,但只能找到使用Angular的示例.有人能告诉我找到这个的正确方向吗?或者在这里发布一个使用post和JSON数据获取JSON响应的快速示例.
请注意,到目前为止,全球fetch
是available on all modern browsers and covers 95% of all web users.如果你需要IE的支持,请阅读原始答案.
MDN Doc | TypeScript Definition
如果该函数在window
或global
上下文中可用,则如下所示:
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中使用原生JavaScript函数来处理HTTP POST请求,请查看YouMightNotNeedJQuery上的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);
});
}
XMLHttpRequest
是一个内置的JavaScript类,包含在TypeScript打字中.