Send GET and POST requests in JavaScript
This post will discuss how to send GET and POST requests in JavaScript.
There are several ways to send GET and POST requests in JavaScript, which are functions of sending and receiving data from a server or an API. Some of the common ways are:
1. Using Fetch API
This is a modern and promise-based function that allows us to make HTTP requests and handle the responses. To send a GET request with the Fetch API, we only need to specify the URL as a parameter. The fetch() function returns a promise that resolves to a response object, which we can then parse as JSON or text. Here’s an example of how we can achieve this:
|
1 2 3 4 5 |
// Send a GET request with the fetch API fetch("https://reqres.in/api/users/1") .then(response => response.json()) // Parse the response as JSON .then(data => console.log(data)) // Do something with the data .catch(error => console.error(error)); // Handle any errors |
We can use the function parameter to specify the POST function, the body parameter to specify the data to be sent, and the headers parameter to specify the content type and other information.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Create an object with some data const data = { "name": "John", "job": "Plumber" }; // Send a POST request with the fetch API fetch("https://reqres.in/api/users", { method: "POST", body: JSON.stringify(data), // Convert the data to a JSON string headers: { "Content-Type": "application/json" // Specify the content type } }) .then(response => response.json()) // Parse the response as JSON .then(data => console.log(data)) // Do something with the data .catch(error => console.error(error)); // Handle any errors |
2. Using XMLHttpRequest object
XMLHttpRequest is an older and callback-based function that allows us to create and send HTTP requests and handle the responses. To send a GET request with the XMLHttpRequest object, we need to create a new instance of the object, open a connection with the URL and the function, send the request, and register an event listener for the response. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Open a connection with the URL and the function xhr.open("GET", "https://reqres.in/api/users/1"); // Send the request xhr.send(); // Register an event listener for the load event xhr.onload = function() { // Check if the status code is 200 (OK) if (xhr.status === 200) { // Parse the response as JSON const data = JSON.parse(xhr.responseText); // Do something with the data console.log(data); } else { // Handle any errors console.error(xhr.statusText); } }; |
We can also use the open() function to specify the POST function and the URL, the setRequestHeader() function to specify the content type and other information, and the send() function to send the data.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Create an object with some data const data = { name: "John", job: "Plumber" }; // Open a connection with the URL and the function xhr.open("POST", "https://reqres.in/api/users"); // Set the request header for the content type xhr.setRequestHeader("Content-Type", "application/json"); // Send the data as a JSON string xhr.send(JSON.stringify(data)); // Register an event listener for the load event xhr.onload = function() { // Check if the status code is 200 (OK) or 201 (CREATED) if (xhr.status === 200 || xhr.status === 201) { // Parse the response as JSON const data = JSON.parse(xhr.responseText); // Do something with the data console.log(data); } else { // Handle any errors console.error(xhr.statusText); } }; |
3. Using Axios Library
We can use an external library or package, such as Axios. It is a popular and promise-based HTTP client that simplifies making network requests. We can use the get() function to send a GET request with the URL and the data as parameters. For example, we can send a GET request using axios like this:
|
1 2 3 4 5 6 |
const axios = require("axios"); // Send a GET request with the axios API axios.get("https://reqres.in/api/users/1") .then((response) => console.log(response.data)) .catch((error) => console.error(error)); |
We can use the post() function to send a POST request with the URL and the data as parameters. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const axios = require('axios'); // Create an object with some data const data = { name: "John", job: "Plumber" }; // Send a POST request with the axios API axios.post('https://reqres.in/api/users/', data) .then(response => console.log(response.data)) .catch(error => console.error(error)); |
That’s all about sending GET and POST requests in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)