Language:

Search

Cómo hacer una petición HTTP en Javascript?

  • Share this:
Cómo hacer una petición HTTP en Javascript?

Introduction

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive, mainly used as a frontend technology for building webpages and apps. 

Also Read: Understanding JavaScript For Loops

The interaction between the frontend and backend of websites is made possible through HTTP requests. Functionalities like updating a record in the database, creating a new record, deleting a picture, and so on, all require an interaction between a server and a client to modify data.

HTTP requests can be used to send or receive data from a server side resource. In this snippet, we'll cover the XMLHttpRequest and fetch API to make HTTP requests in JavaScript.

Also Read: JavaScript Array Map method

Here's an example using XMLHttpRequest

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "https://api.example.com/data.json", true); 
xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; 
xhr.send();

And here's an example using fetch API

Also Read: Best Youtube channels to Learn JavaScript

fetch("https://api.example.com/data.json")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques

Su experiencia en este sitio mejorará si permite el uso de cookies. Cookie Policy