Typescript this http get

Typescript this http get

Make sure to install axios before using the code samples in the article.

You can install axios by opening your terminal in your project’s root directory and running the npm install axios command.

Copied!
# 👇️ if you need to initialize a package.json file npm init -y # ✅ with NPM npm install axios # ✅ with YARN yarn add axios

Here is an example of an HTTP GET request using axios in TypeScript.

Copied!
import axios from 'axios'; type User = id: number; email: string; first_name: string; >; type GetUsersResponse = data: User[]; >; async function getUsers() try // 👇️ const data: GetUsersResponse const data, status > = await axios.getGetUsersResponse>( 'https://reqres.in/api/users', headers: Accept: 'application/json', >, >, ); console.log(JSON.stringify(data, null, 4)); // 👇️ "response status is: 200" console.log('response status is: ', status); return data; > catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > > > getUsers();

If you get the error «Cannot find module ‘axios'», click on the following article and follow the installation instructions.

We defined the type for the response we expect from the server and provided it when using the axios.get method.

The first argument the axios.get() method takes is the URL.

Copied!
axios.get(url, config)

The second argument is a request config object and is not required.

I only included the second argument because you might be making HTTP GET requests to an API that requires authorization. In this case, you might need to set an Authorization header.

If you need to check the response schema, look at this section of the axios GitHub repository.

Copied!
// `data` is the response from the server data: >, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lowercase and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: >, // `config` is the config that was provided to `axios` for the request config: >, // `request` is the request that generated this response request: > >

We destructured the data property from the axios response schema.

Copied!
const data, status > = await axios.getGetUsersResponse>( 'https://reqres.in/api/users', headers: Accept: 'application/json', >, >, );

The data property is the response that was provided by the server.

Another property you might need to use from the response object is status . It represents the status code from the server’s response, e.g. 200 or 404 .

Axios includes a type guard for errors which we used in our catch method.

Copied!
catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > >

If the error is an axios error, we can safely access the message property to get the error message.

Otherwise, the error is typed as unknown and we have to manually check before accessing any properties.

What you might have noticed is that axios automatically parses the JSON from the response as opposed to the built-in fetch() method.

We directly have the parsed response stored in the data variable.

If you want to use the built-in fetch module to make HTTP requests in TypeScript, check out my other article.

# Making HTTP POST requests with Axios in TypeScript

Let’s look at an example HTTP POST request made with axios in TypeScript.

I’ll post the entire code snippet and then we’ll go over it.

Copied!
import axios from 'axios'; type CreateUserResponse = name: string; job: string; id: string; createdAt: string; >; async function createUser() try // 👇️ const data: CreateUserResponse const data, status > = await axios.postCreateUserResponse>( 'https://reqres.in/api/users', name: 'John Smith', job: 'manager' >, headers: 'Content-Type': 'application/json', Accept: 'application/json', >, >, ); console.log(JSON.stringify(data, null, 4)); console.log(status); return data; > catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); // 👇️ error: AxiosError return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > > > createUser();

We used the axios.post method to make an HTTP POST request.

Copied!
axios.post(url, data, config)

We passed the type of the expected response as a generic to the axios.post() method.

Copied!
const data, status > = await axios.postCreateUserResponse>( 'https://reqres.in/api/users', name: 'John Smith', job: 'manager' >, headers: 'Content-Type': 'application/json', Accept: 'application/json', >, >, );

Источник

TypeScript HTTP Request

TypeScript HTTP Request

The http requests in TypeScript are made in order to fetch or bring the data from an external web server or post the data to an external web server. Such requests can be placed using a function called fetch() function, and this fetch function takes two parameters: URL and options where URL is the URL of the website that we are trying to access. The options parameter takes two values, GET and POST, where GET is used to fetch the contents of the website whose URL is specified, and POST is used to post the contents to a website whose URL is specified, and the default value for options is GET.

Web development, programming languages, Software testing & others

Syntax to declare an HTTP Request in TypeScript:

Where URL is the URL of the website that we are trying to access and options parameter takes two values GET and POST where GET is used to fetch the contents of the website whose URL is specified and POST is used to post the contents to a website whose URL is specified and the default value for options is GET.

Working of HTTP Request in TypeScript

  • The http requests in TypeScript are made in order to fetch or bring the data from an external web server or post the data to an external web server.
  • The http requests in TypeScript can be placed using a function called fetch() function.
  • The fetch() function takes two parameters, namely URL and options and returns a Response object.
  • The response object received by using the fetch() function consists of useful information such as text(), headers, json(), status, statusText etc.
  • When the value of options passed as a parameter to the fetch function is POST, we have several options using this parameter: body, method, and headers.

Examples of TypeScript HTTP Request

Given below are the examples of TypeScript HTTP Request:

Example #1

TypeScript program to place a simple http GET request to a website by passing the URL of the website as the parameter to the fetch function and then converting the response from the website into a text format and printing it as the output the screen.

//node fetch module is loaded to be able to make use of fetch function const fetch = require('node-fetch'); //the URL of the website whose contents are to be fetched is passed as the parameter to the fetch function fetch('https://facebook.com') //then() function is used to convert the contents of the website into text format .then(result => result.text()) //the contents of the website in text format is displayed as the output on the screen .then(textformat => console.log(textformat))

TypeScript HTTP Request 1

In the above program, the node fetch module is loaded to be able to make use of the fetch function. Then the URL of the website whose contents are to be fetched is passed as a parameter to the fetch function. Then the () function is used to convert the contents of the website into text format. Then the contents of the website in text format are displayed as the output on the screen.

Example #2

TypeScript program to place a simple http POST request to a website by passing the URL of the website as the parameter to the fetch function and then convert the posted content to the website into a json format and print it as the output on the screen.

//node fetch module is loaded to be able to make use of fetch function const fetch = require('node-fetch'); //the content to be posted to the website is defined let todo = < userId: 01234, title: "SAP BW Hana Consultant", completed: True >; //the URL of the website to which the content must be posted is passed as a parameter to the fetch function along with specifying the method, body and header fetch('https://jsonplaceholder.typicode.com/todos', < method: 'POST', body: JSON.stringify(todo), headers: < 'Content-Type': 'application/json' >>) //then() function is used to convert the posted contents to the website into json format .then(result => result.json()) //the posted contents to the website in json format is displayed as the output on the screen .then(jsonformat=>console.log(jsonformat));

TypeScript HTTP Request 2

In the above program, the node fetch module is loaded to be able to make use of the fetch function. Then the contents to be posted to the website is defined. Then the URL of the website to which the content must be posted is passed as a parameter to the fetch function along with specifying the method, body and header. Then the () function is used to convert the posted contents to the website into json format. Then the posted contents to the website in json format are displayed as the output on the screen.

Rules and Regulations

Given below are the rules and regulations for HTTP requests in TypeScript:

  • The http requests in TypeScript can be placed by making use of a function called fetch() function.
  • The URL of the website whose contents must be fetched or to which the contents must be posted should be passed as a parameter to the fetch() function.
  • The second parameter options to the fetch function are GET methods by default, but if you want to post something to a website, then it is necessary to mention the POST method as an options parameter in the fetch() function.
  • The contents of the website fetched must be converted into text format to display it as the output for the program.
  • The contents to be posted to the website must be converted into json format to be displayed as the output for the program.

We hope that this EDUCBA information on “TypeScript HTTP Request” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Читайте также:  Call popup from javascript
Оцените статью