typescripthttppost

http Post request with Typescript


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.


Solution

  • 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 IE, read the original answer.

    MDN Doc | TypeScript Definition

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

        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 = await streamToString(response.body);
      // and further:
      const asJSON = JSON.parse(asString);  // implicitly 'any', make sure to verify type on runtime.
    }
    

    ... given a helper method such as:

    async function streamToString(array: ReadableStream<Uint8Array>): Promise<string> {
      const utf8 = new TextDecoder("utf-8");
      let asString = '';
      for await (const chunk of array) {  // Can use for-await starting ES 2018
        asString += utf8.decode(chunk);
      }
      return asString;
    }
    

    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 is a built-in JavaScript class and included in the TypeScript typings.