How to Send HTTP Requests Using JavaScript

Nowadays, the interaction between web applications relies on HTTP. For instance, let's say you have an online shop application, and you want to create a new product. You fill in all the necessary information and click Create.

This action will send an HTTP request to the backend, along with all the necessary data, and the backend application will use that data to make changes to the database. After the action is complete, whether successful or not, an HTTP response will be sent back to the frontend, which will act accordingly based on the status of that response.

When these requests and responses are transferred back and forth, they need to follow a certain format so that both ends can understand each other. HTTP was created for this purpose. It is a standard network protocol that enables web applications to understand and communicate with each other.

The HTTP request methods

There are several different methods you could use to send an HTTP request, and each of them serves a different purpose, as shown in the list below:

  • The GET Method

The GET method is used to request data and resources from the server. When you send a GET request, the query parameters are embedded in the URL in name/value pairs like this:

text
http://example.com/index.html?name1=value1&name2=value2

Note that the question mark (?) marks the beginning of a list of parameters. Each parameter forms a key/value pair (name=value), and the ampersand (&) is used to divide two different parameters.

  • The POST Method

The POST method is used to send data to the server, either adding a new resource or updating an existing resource. The parameters are stored in the body of the HTTP request.

text
POST /index.html HTTP/1.1
Host: example.com
name1=value1&name2=value2
  • The DELETE Method

This method removes a resource from the server.

  • The HEAD Method

The HEAD method works just like GET. Except the HTTP response sent from the server will only contain the head but not the body. Meaning if the server is OK with the request, it will give you a 200 OK response but not the resource you requested. You can only retrieve the resource with the GET method.

This is very useful when you are testing whether the server works. Sometimes, the resource takes a long time to be transmitted, and for testing purposes, you only need a 200 OK response to know that everything works properly.

  • THE PUT Method

The PUT method is used to update existing resources, and it is similar to the POST method, with one small difference.

When you PUT a resource that already exists, the old resource will be overwritten. And making multiple identical PUT requests will have the same effect as making it once.

When you POST identical resources, that resource will be duplicated every time the request is made.

What is the fetch API

For a long time, the JavaScript community has lacked a standard way to send HTTP requests. Some people use XMLHttpRequest, aka AJAX, while others prefer external libraries such as Axios or JQuery.

The fetch API was introduced in 2015 as the modern, simplified, and standard way of making HTTP requests using JavaScript. It is natively supported, so there is no need to install any third-party libraries.

How to send a GET request using JavaScript

The fetch API is promise-based, which means it offers a clean and concise syntax for writing asynchronous operations. For example, this is how you can send a GET request using the fetch API.

javascript
fetch("https://api.thedevspace.io/users")
  .then((response) => {
    // If the response is not 2xx, throw an error
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
 
    // If the response is 200 OK, return the response in JSON format.
    return response.json();
  })
  .then((data) => console.log(data)) // You can continue to do something to the response.
  .catch((error) => console.error("Fetch error:", error)); // In case of an error, it will be captured and logged.

You can also include custom options with the request, such as custom headers, authorization tokens, etc.

javascript
fetch("https://api.thedevspace.io/users", {
  headers: {
    "Content-Type": "application/json",
    "Authorization": "your-token-here",
  },
  credentials: "same-origin",
})
  .then(. . .);

How to send a POST request using JavaScript

When sending a POST request, things get a bit more complex because you need to send data to the server with the request body. This could get complicated depending on the kind of data you're sending and your specific use case.

For example, the following code sends JSON data to the backend.

javascript
fetch("https://api.thedevspace.io/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "John Doe",
    email: "johndoe@example.com",
  }),
});

A few things you must pay attention here. First of all, you must explicitly specify the request method. If you leave this out, the default GET method will be used.

Also, the request body only accepts string data, so you must use the stringify() method to convert JSON into a string before assigning it to the request body.

This is also why it is important to include the Content-Type header, which lets whoever is on the receiving end know how to parse the request body.

However, things are usually more complex in practice. For example, when working with web forms, instead of JSON, you are likely using the x-www-form-urlencoded form encoding, in which case the request can be sent like this.

The following example assumes you understand what are event handlers.

javascript
document.addEventListener("DOMContentLoaded", function () {
  const form = document.querySelector("form");
  const usernameInput = document.getElementById("username");
  const emailInput = document.getElementById("email");
 
  const formData = new URLSearchParams();
 
  usernameInput.addEventListener("input", function () {
    formData.set("username", usernameInput.value);
  });
 
  emailInput.addEventListener("input", function () {
    formData.set("email", emailInput.value);
  });
 
  form.addEventListener("submit", async function (event) {
    event.preventDefault(); // Prevent the default form submission action
 
    await fetch("https://api.thedevspace.io/users", {
      method: "POST",
      body: formData.toString(),
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
  });
});

If you need to upload files to the backend, you'll need the multipart/form-data form encoding instead.

javascript
document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("myForm");
  const usernameInput = document.getElementById("username");
  const emailInput = document.getElementById("email");
  const pictureInput = document.getElementById("picture");
 
  const formData = new FormData();
 
  usernameInput.addEventListener("input", function () {
    formData.set("username", usernameInput.value);
  });
 
  emailInput.addEventListener("input", function () {
    formData.set("email", emailInput.value);
  });
 
  pictureInput.addEventListener("change", function () {
    formData.set("picture", pictureInput.files[0]);
  });
 
  form.addEventListener("submit", async function (event) {
    event.preventDefault(); // Prevent the default form submission
 
    await fetch("https://api.thedevspace.io/users", {
      method: "POST",
      body: formData,
    });
  });
});

Note that when using the FormData() to construct the request body, the Content-Type will be locked into multipart/form-data. In this case, it is not necessary to set a custom Content-Type header.

How to send a PUT request using JavaScript

The PUT request works similarly to POST, only you must remember to set method to PUT.

javascript
fetch("https://api.thedevspace.io/users", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    id: "123"
    name: "John Doe",
    email: "johndoe@example.com",
  }),
});

Realistically, you will need to provide an id, or any other keys that enable you to locate the record to be updated in the backend.

How to send a DELETE request using JavaScript

The DELETE request works similarly to PUT, only remember to set method to DELETE.

javascript
fetch("https://api.thedevspace.io/users/123", {
  method: "DELETE",
});

And similarly, remember to provide an id, so that the backend application knows which record to delete.

How to send a request using XMLHttpRequest (AJAX)

Besides fetch(), it is also possible to make an HTTP request using XMLHttpRequest. The following example demonstrates how to make a GET request to the endpoint https://api.thedevspace.io/users.

javascript
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.thedevspace.io/users", true);
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error("Error:", xhr.statusText);
  }
};
xhr.onerror = function () {
  console.error("Request failed");
};
xhr.send();

The syntax is a bit more complex, as XMLHttpRequest relies on callback functions to work with asynchronous operations, which means it is easy to lead to what is known as the callback hell, where you have layers upon layers of callback functions, making your code base difficult to read and maintain.

However, XMLHttpRequest does have some advantages. Due to the fact that XMLHttpRequest is much older compared to fetch(), it is more widely supported. You should consider using XMLHttpRequest when your web app needs to be compatible with older browsers.

How to send a request using external libraries

Aside from the built-in methods, you can also send HTTP requests using third-party libraries. For instance, this is how you can send a GET request using jQuery:

javascript
$.get("https://api.example.com/data", function (data) {
  console.log(data);
}).fail(function (error) {
  console.error("Error:", error);
});

jQuery is one of the most popular JavaScript libraries. It aims to fix the part of JavaScript that is difficult to use, and it has been pretty successful at that.

In recent years, jQuery has lost some popularity as vanilla JavaScript has improved over the years and the problems that used to bother people have been fixed. It is no longer the go-to choice for creating JavaScript applications, especially for newer developers.

Alternatively, you could go with Axios, which is a promise-based HTTP client just like fetch(), and it has been people's favorite for a very long time before fetch() came.

javascript
axios
  .get("https://api.example.com/data")
  .then((response) => console.log(response.data))
  .catch((error) => console.error("Axios error:", error));

Axios and fetch() have very similar syntax as they are both promise-based. The main difference between them is that fetch() is built-in, while Axios requires you to install an external library. However, Axios is much more feature-rich, as it comes with request/response interceptors, automatic JSON handling, and built-in timeouts.

Conclusion

We introduced four different ways you could send HTTP requests using JavaScript in this tutorial. It is up to you to decide which is best for your project.

The fetch API is the modern and standard way of making HTTP requests using JavaScript. It has a relatively simple syntax, which makes your project easier to maintain.

XMLHttpRequest is the legacy method of sending HTTP requests. It is generally not recommended for use in new projects, but if your project needs to be compatible with legacy browsers, XMLHttpRequest might still come in handy.

jQuery is an external package that can do a lot of things, including sending HTTP requests. Although the significance of jQuery has been fading in recent years, it is still used in many older projects, and you might encounter it in your work as a JavaScript developer.

Axios is a third-party library used to send HTTP requests. It has a very similar syntax to the fetch API but comes with a lot more advanced features. It is up to you to decide if you need these features. If not, it is generally recommended to use fetch() instead.

Learn, Build & Launch

With Our Full Stack Dev Roadmap with Next.js Boilerplate

Start for FREE 🎉

Subscribe below to grab our free Full-Stack Web Developer Starter Kit 👇

Also follow us onorwhere we share coding tips daily.

Course Outline
Introduction+
  • 1.Course Introduction
HTML & CSS+
  • 1.Preparations
  • 2.HTML Elements
  • 3.Text Elements
  • 4.Layout Elements
  • 5.Cascading Style Sheet
  • 6.Basic Selectors
  • 7.Advanced Selectors
  • 8.Colors
  • 9.Loading Font
  • 10.Font Customization
  • 11.Text Customization
  • 12.Text Spacing
  • 13.Text Alignment
  • 14.Functions
  • 15.@ Rules
  • 16.Links
  • 17.Lists
  • 18.Tables
  • 19.Forms
  • 20.Form Fields
  • 21.Media Files
  • 22.Aspect Ratio
  • 23.Object Fit
  • 24.Cursor Behavior
  • 25.Scroll Behavior
  • 26.Visibility & Opacity
  • 27.Box Shadow
  • 28.Color Background
  • 29.Image Background
  • 30.Background Attachment
  • 31.Gradient
  • 32.Blend Modes
  • 33.The Box Model
  • 34.Border
  • 35.Padding & Margin
  • 36.Element Size
  • 37.Display Types
  • 38.Overflow
  • 39.Float
  • 40.Position
  • 41.Z index
  • 42.The Column Layout
  • 43.The Grid Layout
  • 44.Grid Flow
  • 45.Grid Gap
  • 46.Grid Spanning
  • 47.Grid Alignment
  • 48.The Flexbox Layout
  • 49.Flex Gap
  • 50.Flex Order
  • 51.Basis, Grow & Shrink
  • 52.Flexbox Alignment
  • 53.Calculator
  • 54.Filters
  • 55.Transforms
  • 56.Transition
  • 57.Transition Timing Functions
  • 58.Transition Delay
  • 59.Animations
  • 60.Animation Iteration Count
  • 61.Animation Direction
  • 62.Animation Fill Mode
  • 63.Responsive Design
  • 64.Viewport
  • 65.Media Query
  • 66.Responsive Media
  • 67.Responsive Text
  • 68.Responsive Layout (Flexbox)
  • 69.Responsive Layout (Grid)
  • 70.Responsive Layout (Legacy)
  • 71.Layout Without Media Query
  • 72.Recreating YouTube
  • 73.Building the Layout
  • 74.Building the Navbar
  • 75.Building the Sidebar
  • 76.Building the Main Section
JavaScript Fundamentals+
  • 1.Introduction
  • 2.Basic Syntax
  • 3.Variables
  • 4.Data Types
  • 5.Numbers & BigInt
  • 6.Strings
  • 7.Boolean Values
  • 8.Undefined & Null
  • 9.Type Conversion
  • 10.If Statements
  • 11.Switch Statements
  • 12.While Loops
  • 13.For Loops
  • 14.Introducing Functions
  • 15.Variable Scope
  • 16.Arrays
  • 17.Mutating Array
  • 18.Searching Array
  • 19.Sorting Array
  • 20.Looping Array
  • 21.Objects
  • 22.Looping Object
  • 23.JSON
  • 24.Symbols
  • 25.Maps
  • 26.Sets
  • 27.Define Functions
  • 28.Function Arguments
  • 29.Rest Parameter & Spread Syntax
  • 30.Error Handling
  • 31.Pure Functions
  • 32.Functions as Value
  • 33.Higher Order Functions
  • 34.Function Factory
  • 35.Function Currying
  • 36.Function Wrapper
  • 37.Recursion
  • 38.Closure
  • 39.Methods
  • 40.Investigating "this"
  • 41.Losing "this"
  • 42.Constructor Functions
  • 43.Getters & Setters
  • 44.Prototypes Introduction
  • 45.Creating Prototypes
  • 46.Inspecting Prototypes
  • 47.Constructor with Prototype
  • 48.The Class Notation
  • 49.Class Inheritance
  • 50.Static Properties
  • 51.Private Properties
  • 52.Object Oriented Programming
  • 53.A Banking App
  • 54.Working with Date
  • 55.The Math Object
  • 56.JavaScript Modules
  • 57.Throwing Errors
  • 58.Asynchronous Programming
  • 59.Promise
  • 60.Resolve Promise
  • 61.Promise Chaining
  • 62.Async & Wait
  • 63.Best Practices
JavaScript in the Frontend+
  • 1.The DOM Tree
  • 2.Selecting Elements in the DOM
  • 3.DOM Navigation
  • 4.Changing Elements
  • 5.Adding Elements
  • 6.Removing Elements
  • 7.Event Handling
  • 8.Event Propagation
  • 9.Some Common Events
  • 10.Image Slider: Creating HTML
  • 11.Image Slider: Adding Styles
  • 12.Image Slider: Adding Scripts
  • 13.Image Slider That "Slides"
  • 14.Regular Expressions
  • 15.Regex Flags
  • 16.Regex Matching Character Sets
  • 17.Regex Boundary
  • 18.Regex Groups & Quantifiers
  • 19.Regex Lookahead & Lookbehind
  • 20.Regex Related Methods
  • 21.Calculator
  • 22.Canvas
JavaScript in the Backend+
  • 1.Setting Up a Dev Environment
  • 2.Network & HTTP
  • 3.A Basic Web App
  • 4.Express.js
  • 5.Routing
  • 6.MVC Architecture
  • 7.The Model Layer
  • 8.CRUD Operations
  • 9.The Controller Layer
  • 10.The View Layer
  • 11.Blog
  • 12.ORM Integration
  • 13.Creating a Post
  • 14.Uploading Files
  • 15.Showing a Post
  • 16.Updating a Post
  • 17.Deleting a Post
  • 18.Database Relations
  • 19.CRUD Tags
  • 20.Adding & Removing Tags
  • 21.Showing Tags & Posts
  • 22.Middleware
  • 23.Browser Data Storage
  • 24.User Registration
  • 25.User Authentication
  • 26.User Authorization
  • 27.User Management
  • 28.Going to Production
React.js+
  • 1.Introducing React.js
  • 2.Setting Up React Project
  • 3.React Project Structure
  • 4.JSX
  • 5.Conditional Rendering
  • 6.List Rendering
  • 7.Adding Styles
  • 8.Components
  • 9.Import & Export Component
  • 10.Variables in Components
  • 11.Props
  • 12."children" Prop
  • 13.Event Handlers
  • 14.Event Handlers & Props
  • 15.Event Propagation
  • 16.Event Prevent Default
  • 17.Introducing State
  • 18.States are Local
  • 19.Object States
  • 20.Multiple States
  • 21.Shared States
  • 22.Form Handling
  • 23.Component Lifecycle
  • 24.Built-In Components
  • 25.Todo List
  • 26.Add New Task
  • 27.Remove Task
  • 28.Edit Task
  • 29.Complete a Task
  • 30.View Pending Tasks
  • 31.Organize State with Reducer
  • 32.The Reducer Function
  • 33.Dispatch Actions
  • 34.Passing Data with Context
  • 35.Context Provider
  • 36.Access Context
  • 37.Use Context with State
  • 38.Manipulate DOM with Refs
  • 39.Side Effects
  • 40.Side Effect Dependencies
  • 41.Side Effect Clean Up
  • 42.Weather App
  • 43.Get Weather by Coordinate
  • 44.Get Weather by City
  • 45.Display Weather by User Location
  • 46.Creating Custom Hooks
  • 47.Other React Hooks
  • 48.Rules of React
  • 49.Building a Full-Stack Blog App
  • 50.Project Setup
  • 51.React Router
  • 52.List Posts
  • 53.Create a New Post
  • 54.Show a Single Post
  • 55.Update a Post
  • 56.Delete a Post
  • 57.Implement Dark Theme
Full-Stack with Next.js+
  • 1.Next.js Basics
  • 2.Routing
  • 3.Pages & Layout
  • 4.Server vs. Client Components
  • 5.API Routes
  • 6.Server Actions
  • 7.Database Integration
  • 8.Data Fetching
  • 9.Error Handling
  • 10.Middleware
  • 11.Links, Navigation & Redirection
  • 12.Images
  • 13.Scripts
  • 14.Fonts
  • 15.Lazy Loading
  • 16.Caching
  • 17.Loading UI
  • 18.SaaS Platform
  • 19.User Authentication
  • 20.Magic Link
  • 21.Custom Emails
  • 22.Protecting Routes
  • 23.OAuth Providers
  • 24.Dashboard
  • 25.Role Based Access Control
  • 26.Payment Integration
  • 27.Pricing Page
  • 28.Stripe Checkout
  • 29.Payment Webhook
AI for Full-Stack Developers+
  • 1.What Are LLMs?
  • 2.Setting Up OpenAI Account
  • 3.Tokens
  • 4.Context Window
  • 5.Compare LLM Models
  • 6.OpenAI Model Playground
  • 7.Building a Chatbot
  • 8.Send Message to OpenAI
  • 9.Talking to GPT-4
  • 10.Talking to GPT-5
  • 11.Response Streaming
  • 12.Sending Data
  • 13.Receiving Data
  • 14.Streaming with Server Sent Events
  • 15.Chatbot Streaming Backend
  • 16.Chatbot Streaming Frontend
  • 17.Prompt Engineering
  • 18.System Prompt
  • 19.Role Switcher
  • 20.Prompting Techniques
  • 21.Structured Output
  • 22.Get Current Weather
  • 23.Tools & Functions
  • 24.Structured Output vs. Tool Calling
  • 25.What is an Agent
  • 26.What is RAG
  • 27.Chunking & Embedding
  • 28.Building a RAG Agent
  • 29.Setting Up the Database
  • 30.Document Processing
  • 31.Split Text into Chunks
  • 32.Generate Embeddings
  • 33.Listing Processed Documents
  • 34.Chat with RAG Agent
  • 35.Semantic Search
  • 36.Generate a Response
Recent Community Articles
  • The Ultimate Guide to Becoming an AI Engineer
  • How to Learn Full-Stack Web Development in 2025 (With Projects)
  • Top Website Optimization Methods in 2025
  • How to Build Interactive Forms Using HTML and CSS
  • How to Create a Modern App with Django and Vue
  • How to Send HTTP Requests Using JavaScript
  • Vue.js Fundamentals
  • How to Reverse a String in JavaScript
  • How to Reverse an Array in JavaScript
  • JavaScript Fundamentals 2025
  • The HTTP request methods
  • What is the fetch API
  • How to send a GET request using JavaScript
  • How to send a POST request using JavaScript
  • How to send a PUT request using JavaScript
  • How to send a DELETE request using JavaScript
  • How to send a request using XMLHttpRequest (AJAX)
  • How to send a request using external libraries
  • Conclusion

Full Stack AI Dev

RoadmapCommunityPricing

SaaS Boilerplate

Next.js BoilerplateDocumentation

Contribute

Write for UsStyle Guide

Free Tools

HTML CompilerJavaScript CompilerNode.js CompilerReact CompilerNext.js Compiler

Legals

Privacy PolicyTerms of ServiceContact Us
© 2026TheDevSpace.io| All Rights Reserved
RoadmapSaaS BoilerplatePricingCommunity
CheatsheetsHTML CompilerJavaScript CompilerNode CompilerReact CompilerNext.js Compiler
Get Started
CourseNext.js BoilerplatePricingCommunity
Freebies
CheatsheetsHTML CompilerJavaScript CompilerNode CompilerReact CompilerNext.js Compiler