Как получить request в javascript

Request

The Request interface of the Fetch API represents a resource request.

You can create a new Request object using the Request() constructor, but you are more likely to encounter a Request object being returned as the result of another API operation, such as a service worker FetchEvent.request .

Constructor

Creates a new Request object.

Instance properties

Stores true or false to indicate whether or not the body has been used in a request yet.

Contains the cache mode of the request (e.g., default , reload , no-cache ).

Contains the credentials of the request (e.g., omit , same-origin , include ). The default is same-origin .

Returns a string describing the request’s destination. This is a string indicating the type of content being requested.

Contains the associated Headers object of the request.

Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE= ).

Contains the request’s method ( GET , POST , etc.)

Contains the mode of the request (e.g., cors , no-cors , same-origin , navigate .)

Contains the mode for how redirects are handled. It may be one of follow , error , or manual .

Contains the referrer of the request (e.g., client ).

Contains the referrer policy of the request (e.g., no-referrer ).

Returns the AbortSignal associated with the request

Contains the URL of the request.

Instance methods

Returns a promise that resolves with an ArrayBuffer representation of the request body.

Returns a promise that resolves with a Blob representation of the request body.

Creates a copy of the current Request object.

Returns a promise that resolves with a FormData representation of the request body.

Returns a promise that resolves with the result of parsing the request body as JSON .

Returns a promise that resolves with a text representation of the request body.

Note: The request body functions can be run only once; subsequent calls will reject with TypeError showing that the body stream has already used.

Examples

In the following snippet, we create a new request using the Request() constructor (for an image file in the same directory as the script), then return some property values of the request:

const request = new Request("https://www.mozilla.org/favicon.ico"); const url = request.url; const method = request.method; const credentials = request.credentials; 

You could then fetch this request by passing the Request object in as a parameter to a fetch() call, for example:

fetch(request) .then((response) => response.blob()) .then((blob) =>  image.src = URL.createObjectURL(blob); >); 

In the following snippet, we create a new request using the Request() constructor with some initial data and body content for an API request which need a body payload:

const request = new Request("https://example.com",  method: "POST", body: '', >); const url = request.url; const method = request.method; const credentials = request.credentials; const bodyUsed = request.bodyUsed; 

Note: The body can only be a Blob , an ArrayBuffer , a TypedArray , a DataView , a FormData , a URLSearchParams , a ReadableStream , or a String object, as well as a string literal, so for adding a JSON object to the payload you need to stringify that object.

You could then fetch this API request by passing the Request object in as a parameter to a fetch() call, for example and get the response:

fetch(request) .then((response) =>  if (response.status === 200)  return response.json(); > else  throw new Error("Something went wrong on API server!"); > >) .then((response) =>  console.debug(response); // … >) .catch((error) =>  console.error(error); >); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 10, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript Get Request – How to Make an HTTP Request in JS

Joel Olawanle

Joel Olawanle

JavaScript Get Request – How to Make an HTTP Request in JS

When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.

This interaction between your frontend application and the backend server is possible through HTTP requests.

There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.

This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.

For this guide, we’ll retrieve posts from the free JSON Placeholder posts API.

There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.

How to Make a GET Request with the Fetch API

The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.

Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.

Let’s create a GET request to get a post from the JSON Placeholder posts API.

fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((json) => console.log(json)); 

This will return a single post which you can now store in a variable and use within your project.

Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.

How to Make a GET Request with Axios

Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.

Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.

To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:

And now you can install Axios to your project by running the following command:

Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.

axios.get("https://jsonplaceholder.typicode.com/posts/1") .then((response) => console.log(response.data)) .catch((error) => console.log(error)); 

Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.

At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.

How to Make a GET Request with XMLHttpRequest

You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.

Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.

Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you’ll send the request, and finally listen to the server’s response.

const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1"); xhr.send(); xhr.responseType = "json"; xhr.onload = () => < if (xhr.readyState == 4 && xhr.status == 200) < console.log(xhr.response); >else < console.log(`Error: $`); > >; 

In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr . You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.

Another method you will use is .send() , which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.

If the client’s state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.

How to Make a GET Request with jQuery

Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:

With jQuery, you can access the GET method $.get() , which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => < console.log(data); >); 

Note: In the callback function, you have access to the request’s data and the request’s status.

You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:

Wrapping Up

In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?

If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.

Источник

Читайте также:  Svg size with css
Оцените статью