make a http request with a custom method in typescript

To make a HTTP request with a custom method in TypeScript, we can use a library like Axios or the native Fetch API.

Using Axios

Example code to make a PATCH request using Axios in TypeScript:

index.ts
import axios, { AxiosResponse } from 'axios';

const url: string = 'https://example.com/api/user/1';
const data = { name: 'John Doe' };

axios.patch(url, data)
  .then((response: AxiosResponse) => {
    console.log(response.data);
  })
  .catch((error: any) => {
    console.error(error);
  });
295 chars
13 lines

In this example, we import the Axios library and use the patch method to make a PATCH request to https://example.com/api/user/1 with the payload of { name: 'John Doe' }. The response is logged to the console, and errors are handled with a .catch() block.

Using Fetch API

Example code to make a PUT request using Fetch API in TypeScript:

index.ts
const url: string = 'https://example.com/api/user/1';
const data = { name: 'John Doe' };

fetch(url, {
  method: 'PUT',
  body: JSON.stringify(data),
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then((response: Response) => {
    return response.json();
  })
  .then((data: any) => {
    console.log(data);
  })
  .catch((error: any) => {
    console.error(error);
  });
388 chars
20 lines

In this example, we use the native Fetch API to make a PUT request to https://example.com/api/user/1 with the payload of { name: 'John Doe' }. The response is parsed as JSON and logged to the console, and errors are handled with a .catch() block. Note that we need to set the Content-Type header to application/json and stringify the data before sending.

gistlibby LogSnag