Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http Post request with Typescript

Tags:

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.

like image 307
Derek Lawrence Avatar asked Feb 27 '18 17:02

Derek Lawrence


People also ask

How do you send a HTTP request in TypeScript?

To make HTTP requests in TypeScript, we use a function known as fetch() . This function takes in two parameters, URL and options. The URL is the link to the webpage we are trying to fetch, whereas, in the options, we send methods that are GET or POST . We can use the GET method to fetch the data from the web server.

How do you pass a request body in TypeScript?

We still have to convert the request body to json, by passing it to the JSON. stringify() method. Notice that we set the Content-Type header to application/json just like we did when making a POST request. The last step is to use a type assertion to set the type of the result variable to the expected response type.

Can we use Axios in TypeScript?

Create an Axios Config File in TypeScriptAxios provides many useful types and can be used to create a config file which we can further use to make REST API calls throughout the application. Copy import Books from './api' // config added in api. ts file const [books, setBooks] = React.


2 Answers

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

like image 145
EyasSH Avatar answered Sep 25 '22 20:09

EyasSH


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

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

like image 20
John Henckel Avatar answered Sep 25 '22 20:09

John Henckel